我们在开发过程中,经常需要进行http请求去调用各种接口和各种文档,比如微信公众号开发过程中,需要进程调用一些接口,像获取AccessToken,获取openid,QQ登录也要调用授权接口,微服务开发有时候也是直接用http请求来操作。
这里笔记一篇Java版本的Http请求工具类,主要是get请求和post请求,并且post请求参数主要是一个json字符串,具体怎么生成json字符串,大家可以用Gson把Map转即可。
Maveny依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
HttpUtils.java
/**
* http请求工具类
* @author lwh
* @date 20181130
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
public class HttpUtils {
private static final Integer CONNECT_TIMEOUT = 5000;//接超时时间,单位毫秒
private static final Integer CONNECT_REQUEST_TIMEOUT = 1000;//从connect Manager(连接池)获取Connection 超时时间,单位毫秒。
private static final Integer SOCKET_TIMEOUT = 5000;//响应时间
/**
* url get请求
* @param url 访问的url
* @return
* @throws Exception
*/
public static String doGet(String url){
String result = "";
System.out.println("get请求的url:"+url);
try {
HttpResponse response = doGet(url, null, CONNECT_TIMEOUT, CONNECT_REQUEST_TIMEOUT, SOCKET_TIMEOUT);
result = getString(response);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("返回的值:"+result);
return result;
}
/**
* url post请求
* @param url 请求的url
* @param json 传输的json信息,建议全部转换成json回来
* @return
* @throws Exception
*/
public static String doPost(String url,String json) {
String result = "";
System.out.println("post请求的url:"+url);
try {
HttpResponse response = doPost(url, json, CONNECT_TIMEOUT, CONNECT_REQUEST_TIMEOUT, SOCKET_TIMEOUT);
result = getString(response);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("返回的值:"+result);
return result;
}
public static HttpResponse doGet(String path,Map<String, String> querys,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
throws Exception {
HttpClient httpClient = wrapClient(path);
HttpGet request = new HttpGet(path);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(ConnectionRequestTimeout)
.setSocketTimeout(responseConnectTimeout).build();
request.setConfig(requestConfig);
return httpClient.execute(request);
}
public static HttpResponse doPost(String path,
Map<String, Object> bodys,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
throws Exception {
HttpClient httpClient = wrapClient(path);
HttpPost request = new HttpPost(path);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
request.setConfig(requestConfig);
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key).toString()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String path,
String jsonBody,Integer connectTimeout,Integer ConnectionRequestTimeout,Integer responseConnectTimeout)
throws Exception {
HttpClient httpClient = wrapClient(path);
HttpPost request = new HttpPost(path);
request.setHeader("Content-Type", "application/json;charset=UTF-8");
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
request.setConfig(requestConfig);
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,"UTF-8");
entity.setContentType("application/json");
request.setEntity(entity);
}
return httpClient.execute(request);
}
/**
* 获取 HttpClient
* @param path
* @return
*/
private static HttpClient wrapClient(String path) {
HttpClient httpClient = HttpClientBuilder.create().build();
if (path != null && path.startsWith("https://")) {
return sslClient();
}
return httpClient;
}
/**
* 在调用SSL之前需要重写验证方法,取消检测SSL
* 创建ConnectionManager,添加Connection配置信息
* @return HttpClient 支持https
*/
private static HttpClient sslClient() {
try {
// 在调用SSL之前需要重写验证方法,取消检测SSL
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
ctx.init(null, new TrustManager[] { trustManager }, null);
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
// 创建Registry
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https",socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
public static String getString(HttpResponse httpResponse) throws IOException {
HttpEntity entity = httpResponse.getEntity();
String resp = EntityUtils.toString(entity, "UTF-8");
return resp;
}
public static void main(String[] args) throws Exception {
String url ="https://www.suibibk.com/blog/579412311547052032/555875030676799488/639387539102236672";
System.out.println(doGet(url));
System.out.println(doPost(url,null));
}
}
注意:post请求传递的json参数,必须接口支持json参数传递,例如下面的springboot请求:
@RequestMapping("/test")
@ResponseBody
public Map test(@RequestBody Model model) {
System.out.println(model);
Map<String,Object> map = new HashMap();
map.put("哈哈哈", "狗子");
return map;
}
@RequestBody 注解
如果单纯的用HttpServletRequest 来接收是接收不了的,如下:
public List<Chapter> getChapters(HttpServletRequest request)
如果也想要接收,就不能传json模式,只能够Map模式。