
httpclient-4.5.jar
httpcore-4.4.1.jar
httpmime-4.5.jar
二、实例
Java代码
package cn.tzz.apache.httpclient
import java.io.File
import java.io.IOException
import java.net.URL
import java.util.ArrayList
import java.util.List
import java.util.Map
import org.apache.http.HttpEntity
import org.apache.http.NameValuePair
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.entity.UrlEncodedFormEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.conn.ssl.DefaultHostnameVerifier
import org.apache.http.conn.util.PublicSuffixMatcher
import org.apache.http.conn.util.PublicSuffixMatcherLoader
import org.apache.http.entity.ContentType
import org.apache.http.entity.StringEntity
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.content.StringBody
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicNameValuePair
import org.apache.http.util.EntityUtils
public class HttpClientUtil {
private RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.build()
private static HttpClientUtil instance = null
private HttpClientUtil(){}
public static HttpClientUtil getInstance(){
if (instance == null) {
instance = new HttpClientUtil()
}
return instance
}
/**
* 发送 post请求
* @param httpUrl 地址
*/
public String sendHttpPost(String httpUrl) {
HttpPost httpPost = new HttpPost(httpUrl)// 创建httpPost
return sendHttpPost(httpPost)
}
/**
* 发送 post请求
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
*/
public String sendHttpPost(String httpUrl, String params) {
HttpPost httpPost = new HttpPost(httpUrl)// 创建httpPost
try {
//设置参数
StringEntity stringEntity = new StringEntity(params, "UTF-8")
stringEntity.setContentType("application/x-www-form-urlencoded")
httpPost.setEntity(stringEntity)
} catch (Exception e) {
e.printStackTrace()
}
return sendHttpPost(httpPost)
}
/**
* 发送 post请求
* @param httpUrl 地址
* @param maps 参数
*/
public String sendHttpPost(String httpUrl, Map<String, String>maps) {
HttpPost httpPost = new HttpPost(httpUrl)// 创建httpPost
// 创建参数队列
List<NameValuePair>nameValuePairs = new ArrayList<NameValuePair>()
for (String key : maps.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)))
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"))
} catch (Exception e) {
e.printStackTrace()
}
return sendHttpPost(httpPost)
}
/**
* 发送 post请求(带文件)
* @param httpUrl 地址
* @param maps 参数
* @param fileLists 附件
*/
public String sendHttpPost(String httpUrl, Map<String, String>maps, List<File>fileLists) {
HttpPost httpPost = new HttpPost(httpUrl)// 创建httpPost
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create()
for (String key : maps.keySet()) {
meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN))
}
for(File file : fileLists) {
FileBody fileBody = new FileBody(file)
meBuilder.addPart("files", fileBody)
}
HttpEntity reqEntity = meBuilder.build()
httpPost.setEntity(reqEntity)
return sendHttpPost(httpPost)
}
/**
* 发送Post请求
* @param httpPost
* @return
*/
private String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null
CloseableHttpResponse response = null
HttpEntity entity = null
String responseContent = null
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault()
httpPost.setConfig(requestConfig)
// 执行请求
response = httpClient.execute(httpPost)
entity = response.getEntity()
responseContent = EntityUtils.toString(entity, "UTF-8")
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close()
}
if (httpClient != null) {
httpClient.close()
}
} catch (IOException e) {
e.printStackTrace()
}
}
return responseContent
}
/**
* 发送 get请求
* @param httpUrl
*/
public String sendHttpGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl)// 创建get请求
return sendHttpGet(httpGet)
}
/**
* 发送 get请求Https
* @param httpUrl
*/
public String sendHttpsGet(String httpUrl) {
HttpGet httpGet = new HttpGet(httpUrl)// 创建get请求
return sendHttpsGet(httpGet)
}
/**
* 发送Get请求
* @param httpPost
* @return
*/
private String sendHttpGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null
CloseableHttpResponse response = null
HttpEntity entity = null
String responseContent = null
try {
// 创建默认的httpClient实例.
httpClient = HttpClients.createDefault()
httpGet.setConfig(requestConfig)
// 执行请求
response = httpClient.execute(httpGet)
entity = response.getEntity()
responseContent = EntityUtils.toString(entity, "UTF-8")
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close()
}
if (httpClient != null) {
httpClient.close()
}
} catch (IOException e) {
e.printStackTrace()
}
}
return responseContent
}
/**
* 发送Get请求Https
* @param httpPost
* @return
*/
private String sendHttpsGet(HttpGet httpGet) {
CloseableHttpClient httpClient = null
CloseableHttpResponse response = null
HttpEntity entity = null
String responseContent = null
try {
// 创建默认的httpClient实例.
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()))
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher)
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build()
httpGet.setConfig(requestConfig)
// 执行请求
response = httpClient.execute(httpGet)
entity = response.getEntity()
responseContent = EntityUtils.toString(entity, "UTF-8")
} catch (Exception e) {
e.printStackTrace()
} finally {
try {
// 关闭连接,释放资源
if (response != null) {
response.close()
}
if (httpClient != null) {
httpClient.close()
}
} catch (IOException e) {
e.printStackTrace()
}
}
return responseContent
}
}
代码如下:
package org.apache.http.examples.client
import java.net.URI
import java.util.List
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.client.methods.RequestBuilder
import org.apache.http.cookie.Cookie
import org.apache.http.impl.client.BasicCookieStore
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin { public static void main(String[] args) throws Exception { BasicCookieStore cookieStore = new BasicCookieStore()
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build()
try {
HttpGet httpget = new HttpGet("https://someportal/")
CloseableHttpResponse response1 = httpclient.execute(httpget)
try {HttpEntity entity = response1.getEntity()
System.out.println("Login form get: " + response1.getStatusLine())
EntityUtils.consume(entity)
System.out.println("Initial set of cookies:")
List<Cookie>cookies = cookieStore.getCookies()
if (cookies.isEmpty()) {System.out.println("None")} else {for (int i = 0i <cookies.size()i++) { System.out.println("- " + cookies.get(i).toString()) }} } finally {response1.close()}
HttpUriRequest login = RequestBuilder.post()
.setUri(new URI("https://someportal/"))
.addParameter("IDToken1", "username")
addParameter("IDToken2", "password")
.build()CloseableHttpResponse response2 = httpclient.execute(login)
try {HttpEntity entity = response2.getEntity()
System.out.println("Login form get: " + response2.getStatusLine()) EntityUtils.consume(entity)
System.out.println("Post logon cookies:")
List<Cookie>cookies = cookieStore.getCookies() for (int i = 0i <cookies.size()
i++) {}finally { response2.close()
finally}
JAVA
Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于PC、数据中心、游戏控制台、科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。
定义一个简单的restful接口 @RestController public class TestController { @RequestMapping(value = "testPost", method = RequestMethod.POST) public ResponseBean testPost(@RequestBody RequestBean requestBean) { ResponseBean responseBean = new ResponseBean()responseBean.setRetCode("0000")responseBean.setRetMsg("succ")return responseBean} } 使用RestTemplate访问该服务 //请求地址 String url = ""//入参 RequestBean requestBean = new RequestBean()requestBean.setTest1("1")requestBean.setTest2("2")requestBean.setTest3("3")RestTemplate restTemplate = new RestTemplate()ResponseBean responseBean = restTemplate.postForObject(url, requestBean, ResponseBean.class)从这个例子可以看出,使用restTemplate访问restful接口非常的简单粗暴无脑。(url, requestMap, ResponseBean.class)这三个参数分别代表 请求地址、请求参数、HTTP响应转换被转换成的对象类型。 RestTemplate方法的名称遵循命名约定,第一部分指出正在调用什么HTTP方法,第二部分指示返回的内容。本例中调用了restTemplate.postForObject方法,post指调用了HTTP的post方法,Object指将HTTP响应转换为您选择的对象类型。还有其他很多类似的方法,有兴趣的同学可以参考官方api。 三.手动指定转换器(HttpMessageConverter) 我们知道,调用reseful接口传递的数据内容是json格式的字符串,返回的响应也是json格式的字符串。然而restTemplate.postForObject方法的请求参数RequestBean和返回参数ResponseBean却都是java类。是RestTemplate通过HttpMessageConverter自动帮我们做了转换的 *** 作。 默认情况下RestTemplate自动帮我们注册了一组HttpMessageConverter用来处理一些不同的contentType的请求。 如StringHttpMessageConverter来处理text/plainMappingJackson2HttpMessageConverter来处理application/jsonMappingJackson2XmlHttpMessageConverter来处理application/xml。 你可以在org.springframework.http.converter包下找到所有spring帮我们实现好的转换器。 如果现有的转换器不能满足你的需求,你还可以实现org.springframework.http.converter.HttpMessageConverter接口自己写一个。详情参考官方api。 选好了HttpMessageConverter后怎么把它注册到我们的RestTemplate中呢。 RestTemplate restTemplate = new RestTemplate()//获取RestTemplate默认配置好的所有转换器 List<HttpMessageConverter<?>>messageConverters = restTemplate.getMessageConverters()//默认的MappingJackson2HttpMessageConverter在第7个 先把它移除掉 messageConverters.remove(6)//添加上GSON的转换器 messageConverters.add(6, new GsonHttpMessageConverter())这个简单的例子展示了如何使用GsonHttpMessageConverter替换掉默认用来处理application/json的MappingJackson2HttpMessageConverter。 四.设置底层连接方式 要创建一个RestTemplate的实例,您可以像上述例子中简单地调用默认的无参数构造函数。这将使用java.NET包中的标准Java类作为底层实现来创建HTTP请求。 但很多时候我们需要像传统的HttpClient那样设置HTTP请求的一些属性。RestTemplate使用了一种很偷懒的方式实现了这个需求,那就是直接使用一个HttpClient作为底层实现...... //生成一个设置了连接超时时间、请求超时时间、异常最大重试次数的httpClient RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000).setSocketTimeout(30000).build()HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(config).setRetryHandler(new DefaultHttpRequestRetryHandler(5, false))HttpClient httpClient = builder.build()//使用httpClient创建一个ClientHttpRequestFactory的实现 ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient)//ClientHttpRequestFactory作为参数构造一个使用作为底层的RestTemplate RestTemplate restTemplate = new RestTemplate(requestFactory)五.设置拦截器(ClientHttpRequestInterceptor) 有时候我们需要对请求做一些通用的拦截设置,这就可以使用拦截器进行处理。拦截器需要我们实现org.springframework.http.client.ClientHttpRequestInterceptor接口自己写。 举个简单的例子,写一个在header中根据请求内容和地址添加令牌的拦截器。 public class TokenInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { //请求地址 String checkTokenUrl = request.getURI().getPath()//token有效时间 int ttTime = (int) (System.currentTimeMillis() / 1000 + 1800)//请求方法名 POST、GET等 String methodName = request.getMethod().name()//请求内容 String requestBody = new String(body)//生成令牌 此处调用一个自己写的方法,有兴趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程无关,就不贴出来了 String token = TokenHelper.generateToken(checkTokenUrl, ttTime, methodName, requestBody)//将令牌放入请求header中 request.getHeaders().add("X-Auth-Token",token)return execution.execute(request, body)} } 创建RestTemplate实例的时候可以这样向其中添加拦截器 RestTemplate restTemplate = new RestTemplate()//向restTemplate中添加自定义的拦截器 restTemplate.getInterceptors().add(new TokenInterceptor())欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)