RestTemplate是spring特有的,在spring项目中直接注入使用即可,HttpClient是 Apache Jakarta Common的。
一、HttpClient
1.1使用
第一步:添加依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
第二步:创建HttpClient类的对象
有两种方式:
HttpClients和HttpClientBuilder这两种方式
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// 上面两种是一样的,都是i使用默认的配置,下面你这种是使用自己设置配置
CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
第三步:根据不同restful风格的请求,来调用不同的方法
1. 创建http GET请求
HttpGet httpGet = new HttpGet("http://www.oschina.net/");
2. 创建http GET请求 带有参数的
URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "数据库").build();
HttpGet httpGet = new HttpGet(uri);
3. 创建post请求
HttpPost httpPost = new HttpPost("http://www.oschina.net/");
4. 创建post请求 带有参数的
例子:
HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
// 设置2个post参数,一个是scope、一个是q
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 将请求实体设置到httpPost对象中
httpPost.setEntity(formEntity);
第四步:httpclient对象发送请求对象
CloseableHttpResponse response = httpclient.execute(请求对象);
比如:
CloseableHttpResponse response = httpclient.execute(httpGet);
CloseableHttpResponse response = httpclient.execute(httpPost);
第五步:关闭资源
在finally
response.close();
httpclient.close();
拓展:返回in类型的响应码
response.getStatusLine().getStatusCode()
1.2封装通用工具类HttpClientUtils
package org.chu.ego.base.utils;
import java.io.IOException;
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.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.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* --发送get请求的api
* CloseableHttpClient类 ,client实现类
* HttpClients类 ,client工具类,用于创建客户端对象。
* CloseableHttpResponse接口,请求的响应对象
* URIBuilder类 :url构建类,用于设置get请求的路径变量
* HttpGet类 :get请求的发送对象
* EntityUtils类 实体处理类
*
* --发送post 请求使用的api
* CloseableHttpClient类
* HttpClientBuilder client构建对象,用于创建客户端对象。
* LaxRedirectStrategy类,post请求重定向的策略
* CloseableHttpResponse 请求的响应对象
* HttpPost post请求的发送对象
* NameValuePair 类,用于设置参数值
* UrlEncodedFormEntity:用于设置表单参数给发送对象HttpPost
*
* @author ranger
*
*/
public class HttpClientUtils {
public static String doGet(String url,Map<String, String> params){
//获取httpclient客户端
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if(null!=params){
for (String key:params.keySet()) {
builder.setParameter(key, params.get(key));
}
}
HttpGet get = new HttpGet(builder.build());
response = httpclient.execute(get);
System.out.println(response.getStatusLine());
if(200==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
resultString = EntityUtils.toString(entity, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null!=response){
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=httpclient){
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resultString;
}
public static String doGet(String url){
return doGet(url, null);
}
public static String doPost(String url,Map<String,String> params){
/**
* 在4.0及以上httpclient版本中,post需要指定重定向的策略,如果不指定则按默认的重定向策略。
*
* 获取httpclient客户端
*/
CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();
String resultString = "";
CloseableHttpResponse response = null;
try {
HttpPost post = new HttpPost(url);
List<NameValuePair> paramaters = new ArrayList<>();
if(null!=params){
for (String key : params.keySet()) {
paramaters.add(new BasicNameValuePair(key,params.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity (paramaters);
post.setEntity(formEntity);
}
/**
* HTTP/1.1 403 Forbidden
* 原因:
* 有些网站,设置了反爬虫机制
* 解决的办法:
* 设置请求头,伪装浏览器
*/
post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
response = httpclient.execute(post);
System.out.println(response.getStatusLine());
if(200==response.getStatusLine().getStatusCode()){
HttpEntity entity = response.getEntity();
resultString = EntityUtils.toString(entity, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(null!=response){
try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=httpclient){
try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resultString;
}
public static String doPost(String url){
return doPost(url, null);
}
}
二、RestTemplate
先自定义一个bean
package com.zykj.newsell.config;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
// @Bean
// public RestTemplate restTemplate(ClientHttpRequestFactory factory){
// return new RestTemplate(factory);
// }
//
// @Bean
// public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
// SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
// factory.setConnectTimeout(15000);
// factory.setReadTimeout(5000);
// return factory;
// }
@Bean
public ClientHttpRequestFactory httpRequestFactory() {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(httpRequestFactory());
}
@Bean
public HttpClient httpClient() {
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(3000);
connectionManager.setDefaultMaxPerRoute(1000);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
return HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(connectionManager)
.build();
}
}
使用的时候直接注入,前提是这个使用者交给了ioc容器管理(类似@Component)
@Autowired
private RestTemplate restTemplate;
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer");
HttpEntity entity = new HttpEntity(body.toString() , headers);
ResponseEntity<Object> responseEntity = restTemplate.postForEntity("http://a1/users/{username}/password", entity, null, username);
return responseEntity.getStatusCodeValue() == 200;
RestTemplate旗下有很多方法,可以查看这[RestTemplate]RestTemplate