博文简介:
由于工作内容频繁对接第三方系统,用到HTTP协议进行数据传输。
官方地址:Apache HttpComponents – Apache HttpComponents
组件版本:org.apache.httpcomponents:httpclient:4.5.2
已支持集:SSL + 自定义参数 + Header 的配置 + httpClinet配置代理
已实现集:
1. GET 以URL参数编码发送
2. POST 以请求体JSON发送
3. POST 以表单的形式发送
工具函数:(示例)
public class HttpUtil {
// GET URL编码指定字符集 ----------
// url : 资源地址定位 ; param : url?后的参数 ; charSet : URL编码使用字符集,例如:UTF-8
public static String get(String url, Map urlParam, Map header, String charSet, boolean ssl) {
CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
HttpGet httpGet = new HttpGet(charSet == null ? addParams2Url(url, urlParam) : addParams2UrlWithCharSet(url, urlParam, charSet));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
httpGet.setConfig(requestConfig);
try {
// send get request : 发送GET请求
httpGet.setHeaders(createHeader(header));
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) return null;
// do something useful with response body : 业务逻辑
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
return res;
} catch (Exception e) {
} finally {
try {
httpClient.close();
} catch (IOException e) {
}
}
return null;
}
private static String addParams2Url(String url, Map params) {
return addParams2UrlWithCharSet(url, params, null);
}
private static String addParams2UrlWithCharSet(String url, Map params, String charSet) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder();
try {
for (Map.Entry entry : params.entrySet()) {
sb.append("&").append(entry.getKey()).append("=");
sb.append(charSet == null ? entry.getValue() : URLEncoder.encode(entry.getValue(), charSet));
}
if (!url.contains("?")) {
sb.deleteCharAt(0).insert(0, "?");
}
} catch (Exception e) {
}
return url + sb;
}
// POST 以请求体JSON发送数据--------------------
public static String postJson(String url, Map urlParam, Map header, String data, boolean ssl) {
CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
HttpPost httpPost = new HttpPost(addParams2Url(url, urlParam));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
httpPost.setConfig(requestConfig);
try {
httpPost.setHeaders(createHeader(header));
httpPost.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) return null;
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
response.close();
return res;
} catch (Exception e) {
} finally {
try {
httpClient.close();
} catch (Exception e) {
}
}
return null;
}
// POST 以表单的形式发送数据-----------
public static String postForm(String url, Map urlParam, Map header, Map data, boolean ssl) {
CloseableHttpClient httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
HttpPost httpPost = new HttpPost(addParams2Url(url, urlParam));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
httpPost.setConfig(requestConfig);
try {
// config header content-type is application/x-www-form-urlencoded : 配置HTTP的Header:content-type
header = header != null ? header : new HashMap<>();
ContentType APPLICATION_FORM_URLENCODED_UTF8 = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8);
header.put("Content-Type", APPLICATION_FORM_URLENCODED_UTF8.toString());
httpPost.setHeaders(createHeader(header));
// add key-value pair to entity : 设置参数到请求体中
List list = new ArrayList<>();
for (Map.Entry entry : data.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
httpPost.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) return null;
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
response.close();
return res;
} catch (Exception e) {
} finally {
try {
httpClient.close();
} catch (Exception e) {
}
}
return null;
}
// HTTPS client 创建 --------------------
public static CloseableHttpClient getHttpClient() {
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext context = null;
try {
context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[]{trustManager}, null);
return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(context)).build();
} catch (Exception e) {
}
return null;
}
// 批量创建请求头 --------------------
private static Header[] createHeader(Map header) {
if (header == null || header.isEmpty()) return null;
List headers = new ArrayList<>();
for (String key : header.keySet()) {
headers.add(new BasicHeader(key, header.get(key)));
}
return headers.toArray(new Header[]{});
}
}
配置代理(示例):
public class ClientExecuteProxy {
public static void main(String[] args)throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost target = new HttpHost("httpbin.org", 443, "https");
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet request = new HttpGet("/");
request.setConfig(config);
System.out.println("Executing request " + request.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, request);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
public class ClientProxyAuthentication {
public static void main(String[] args) throws Exception {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope("localhost", 8888),
new UsernamePasswordCredentials("squid", "squid"));
credsProvider.setCredentials(
new AuthScope("httpbin.org", 80),
new UsernamePasswordCredentials("user", "passwd"));
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider).build();
try {
HttpHost target = new HttpHost("httpbin.org", 80, "http");
HttpHost proxy = new HttpHost("localhost", 8888);
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
httpget.setConfig(config);
System.out.println("Executing request " + httpget.getRequestLine() + " to " + target + " via " + proxy);
CloseableHttpResponse response = httpclient.execute(target, httpget);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
参考地址:
1. 官网示例:Apache HttpComponents – HttpClient Examples
2. 异步处理:Apache HttpComponents – HttpAsyncClient Quick Start
变更记录:
2022-11-13 : 初稿发布
2022-12-26 :简化实现类的封装,扩展 "配置代理" 及 "代理认证"
** 希望得到你的参与和支持。 如果内容有描述不恰当的地方,请指出。 谢谢!**