JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是,JDK 库本身提供的功能还不够丰富。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本。
这里实现了几种常见的请求方式,包括请求、响应超时的设置;
所需jar包:httpclient-4.5.7.jar(其他版本的也可以,最好使用4.0以上的版本,因为不同版本的实现方式有部分差别);
官网下载地址:http://hc.apache.org/downloads.cgi
我的资源库下载地址:httpclient-4.5.7.jar
1.普通post请求;
2.json格式参数的请求;
3.设置代理的请求;
package com.common.utils.http;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpHost;
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.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
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;
/**
* httpClient请求
* @author zhaoheng
* @date 2019-03-07
*/
public class HttpReq {
/**
* POST请求
* @param url 请求地址
* @param socketTimeout 响应超时时间,根据业务而定,单位毫秒;
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
* @param param 请求参数map集合
* @return
*/
public static String doPost(String url, int socketTimeout, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 设置请求超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间,单位毫秒。
.setConnectionRequestTimeout(1000) // 从连接池获取到连接的超时,单位毫秒。
.setSocketTimeout(socketTimeout).build(); // 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
httpPost.setConfig(requestConfig);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
System.out.println("响应超时!!!");
}
} finally {
// 释放资源
try {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* POST请求(带json参数)
* @param url 请求地址
* @param socketTimeout 响应超时时间,根据业务而定,单位毫秒;
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
* @param jsonParam json参数
* @return
*/
public static String doPostJson(String url, int socketTimeout, String jsonParam) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 设置请求超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间,单位毫秒。
.setConnectionRequestTimeout(1000) // 从连接池获取到连接的超时,单位毫秒。
.setSocketTimeout(socketTimeout).build(); // 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
httpPost.setConfig(requestConfig);
// 创建请求内容
StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
System.out.println("响应超时!!!");
}
} finally {
// 释放资源
try {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 需要设置代理POST请求(带json参数)
* @param proxyIp 代理IP
* @param port 端口号
* @param tcp 协议(例:http、https)
* @param url 请求地址
* @param socketTimeout 响应超时时间,根据业务而定,单位毫秒;
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
* @param jsonParam json参数
* @return
*/
public static String doProxyPostJson(String proxyIp,int port,String tcp, String url,int socketTimeout, String jsonParam) {
//设置代理IP、端口、协议
HttpHost proxy = new HttpHost(proxyIp, port, tcp);
//把代理设置到请求配置
RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
//实例化CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 设置请求超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间,单位毫秒。
.setConnectionRequestTimeout(1000) // 从连接池获取到连接的超时,单位毫秒。
.setSocketTimeout(socketTimeout).build(); // 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
httpPost.setConfig(requestConfig);
// 创建请求内容
StringEntity entity = new StringEntity(jsonParam, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
System.out.println("响应超时!!!");
}
} finally {
// 释放资源
try {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 需要设置代理的 POST请求
* @param proxyIp 代理IP
* @param port 端口号
* @param tcp 协议(例:http、https)
* @param url 请求地址
* @param socketTimeout 响应超时时间,根据业务而定,单位毫秒;
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用
* @param param 请求参数map集合
* @return
*/
public static String doProxyPost(String proxyIp,int port,String tcp, String url, int socketTimeout, Map<String, String> param) {
//设置代理IP、端口、协议
HttpHost proxy = new HttpHost(proxyIp, port, tcp);
//把代理设置到请求配置
RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
//实例化CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 设置请求超时
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) // 设置连接超时时间,单位毫秒。
.setConnectionRequestTimeout(1000) // 从连接池获取到连接的超时,单位毫秒。
.setSocketTimeout(socketTimeout).build(); // 请求获取数据的超时时间,单位毫秒; 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
httpPost.setConfig(requestConfig);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
if (e instanceof SocketTimeoutException) {
System.out.println("响应超时!!!");
}
} finally {
// 释放资源
try {
if (null != httpClient) {
httpClient.close();
}
if (null != response) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 测试方法
* @param args
*/
public static void main(String[] args) {
// 测试post请求
String url = "http://127.0.0.1:8080/download/TestCon/test01";
Map<String, String> param = new HashMap<String, String>();
param.put("name", "welcome");
String result = HttpReq.doPost(url,3000, param);
System.out.println("result:"+result);
// 测试json参数请求
String url2 = "http://127.0.0.1:8080/download/TestCon/test02";
String jsonParam = "{\"fileName\":\"httpClient.jar\",\"fileSize\":\"1024\"}";
String result2 = HttpReq.doPostJson(url2,5000, jsonParam);
System.out.println("result2:"+result2);
// 代理请求测试
String url3 = "https://www.baidu.com";
Map<String, String> param3 = new HashMap<String, String>();
String result3 = HttpReq.doProxyPost("代理ip", 8080, "http", url3,5000, param3);
System.out.println(result3);
}
}