本文将为您提供关于HttpClientUtil工具类的详细介绍,我们还将为您解释http工具包的相关知识,同时,我们还将为您提供关于00037-java的http请求工具类,HttpClientUti
本文将为您提供关于HttpClientUtil 工具类的详细介绍,我们还将为您解释http工具包的相关知识,同时,我们还将为您提供关于00037-java 的http请求工具类,HttpClientUtils、C#操作HttpClient工具类库、coding++ :HttpClientUtils 封装、httpClient 3.1 工具类的实用信息。
本文目录一览:- HttpClientUtil 工具类(http工具包)
- 00037-java 的http请求工具类,HttpClientUtils
- C#操作HttpClient工具类库
- coding++ :HttpClientUtils 封装
- httpClient 3.1 工具类
HttpClientUtil 工具类(http工具包)
/*
*
*
* FileName: s.java
*
* Description:TODO(用一句话描述该文件做什么)
*
* Created: jiangzhanghong 2017年11月14日
*
* |--------------------------------------------------History---------------------------------------------------|
* | |
* |-----Author-----------|-------Date-------|----Version----|----------------------------Desc----------------------------|
* | jiangzhanghong | 2017年11月14日 | 1.0 | Create
* |------------------------------------------------------------------------------------------------------------|
*/
package com.dinfo.app.basic.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
*
* @author <a href="mailto:jiangzhanghong1@ultrapower.com.cn">jiangzhanghong</a>
* @version 1.0
* @date 2017年11月14日
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.UnsupportedCharsetException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 封装了一些采用HttpClient发送HTTP请求的方法
*
* @see 本工具所采用的是最新的HttpComponents-Client-4.2.1
*/
@Component
public class HttpClientUtil {
private HttpClientUtil() {
}
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static int connectTimeout=6000;
private static int socketTimeout=60000;
private static int connectionRequestTimeout=6000;
public static void main(String[] args) {
try {
System.out.println(HttpClientUtil.sendGetRequest("http://baidu.com", null));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param connectTimeout the connectTimeout to set
*/
@Value("${httpclient.connectTimeout:6000}")
public void setConnectTimeout(int connectTimeout) {
HttpClientUtil.connectTimeout = connectTimeout;
}
/**
* @param socketTimeout the socketTimeout to set
*/
@Value("${httpclient.socketTimeout:60000}")
public void setSocketTimeout(int socketTimeout) {
HttpClientUtil.socketTimeout = socketTimeout;
}
/**
* @param connectionRequestTimeout the connectionRequestTimeout to set
*/
@Value("${httpclient.connectionRequestTimeout:6000}")
public void setConnectionRequestTimeout(int connectionRequestTimeout) {
HttpClientUtil.connectionRequestTimeout = connectionRequestTimeout;
}
/**
* 发送HTTP_GET请求
*
* @see 该方法会自动关闭连接,释放资源
* @param requestURL
* 请求地址(含参数)
* @param decodeCharset
* 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendGetRequest(String reqURL, String decodeCharset) throws ClientProtocolException, IOException {
long responseLength = 0; // 响应长度
String responseContent = null; // 响应内容
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建默认的httpClient实例
HttpGet httpGet = new HttpGet(reqURL); // 创建org.apache.http.client.methods.HttpGet
//设置超时
setTimeout(httpGet);
httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); //解决get请求响应返回中文乱码问题
try {
HttpResponse response = httpClient.execute(httpGet); // 执行GET请求
HttpEntity entity = response.getEntity(); // 获取响应实体
if (null != entity) {
responseLength = entity.getContentLength();
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity); // Consume response content
}
System.out.println("请求地址: " + httpGet.getURI());
System.out.println("响应状态: " + response.getStatusLine());
System.out.println("响应长度: " + responseLength);
System.out.println("响应内容: " + responseContent);
} finally {
httpClient.close();
}
return responseContent;
}
/**
* ConnectTimeout 连接建立时间,三次握手完成时间
* SocketTimeout 数据传输过程中数据包之间间隔的最大时间
* ConnectionRequestTimeout httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间
* @param base
*/
private static void setTimeout(HttpRequestBase base){
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
.setSocketTimeout(socketTimeout).build();
base.setConfig(requestConfig);
}
/**
* 发送HTTP_POST请求
*
* @see 该方法为<code>sendPostRequest(String,String,boolean,String,String)</code>的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
* ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
* @param isEncoder
* 用于指明请求数据是否需要UTF-8编码,true为需要
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder) throws ClientProtocolException, IOException {
return sendPostRequest(reqURL, sendData, isEncoder, null, null);
}
/**
* 发送HTTP_POST请求
*
* @see 该方法会自动关闭连接,释放资源
* @see 当<code>isEncoder=true</code>时,其会自动对<code>sendData</code>中的[中文][|][
* ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
* 请求地址
* @param sendData
* 请求参数,若有多个参数则应拼接成param11=value11&22=value22&33=value33的形式后,传入该参数中
* @param isEncoder
* 请求数据是否需要encodeCharset编码,true为需要
* @param encodeCharset
* 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset
* 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendPostRequest(String reqURL, String sendData, boolean isEncoder, String encodeCharset,
String decodeCharset) throws ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
setTimeout(httpPost);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
if (isEncoder) {
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (String str : sendData.split("&")) {
formParams.add(new BasicNameValuePair(str.substring(0, str.indexOf("=")),
str.substring(str.indexOf("=") + 1)));
}
httpPost.setEntity(new StringEntity(
URLEncodedUtils.format(formParams, encodeCharset == null ? "UTF-8" : encodeCharset)));
} else {
httpPost.setEntity(new StringEntity(sendData));
}
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
/**
* 支持单个文件上传
* @param reqURL 请求url
* @param bytes 传递的二进制内容
* @param fileparm 参数名称
* @param decodeCharset
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws Exception
*/
public static String sendPostByte(String reqURL, byte[] bytes, String fileparm,String filename,
String decodeCharset) throws ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
setTimeout(httpPost);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody(fileparm, bytes, ContentType.create("multipart/form-data","UTF-8"), filename);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
/**
* 单个文件上传,file方式
* @param reqURL
* @param file
* @param fileparm
* @param decodeCharset
* @return
* @throws UnsupportedCharsetException
* @throws IOException
* @throws ClientProtocolException
* @throws Exception
*/
public static String sendPostFile(String reqURL,File file, String fileparm,
String decodeCharset) throws UnsupportedCharsetException, ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
setTimeout(httpPost);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setCharset(CharsetUtils.get("UTF-8")); //设置编码,解决上传文件名乱码问题
builder.addBinaryBody(fileparm, new FileInputStream(file), ContentType.create("multipart/form-data","UTF-8"), file.getName());
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
public static String sendPostMutipart(String reqURL, List<byte[]> bytes, List<String> fileparams,List<String> fileNames,List<String> paramNames,List<String> paramValues,
String decodeCharset) throws ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
setTimeout(httpPost);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setCharset(CharsetUtils.get("UTF-8"));
for (int i = 0; i < bytes.size(); i++) {
builder.addBinaryBody(fileparams.get(i), bytes.get(i), ContentType.create("multipart/form-data","UTF-8"), fileNames.get(i));
}
for (int i = 0; i < paramNames.size(); i++) {
builder.addTextBody(paramNames.get(i), paramValues.get(i), ContentType.create("multipart/form-data","UTF-8"));
}
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
*
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][
* ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
* 请求地址
* @param params
* 请求参数
* @param encodeCharset
* 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset
* 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendPostRequest(String reqURL, Map<String, String> params, String encodeCharset,
String decodeCharset) throws ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
if(params==null){
params=new HashMap<String, String>();
}
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
//setTimeout(httpPost);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 创建参数队列
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset == null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
/**
* 发送HTTPS_POST请求
* @throws IOException
* @throws ClientProtocolException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*
* @see 该方法为<code>sendPostSSLRequest(String,Map<String,String>,String,String)</code>方法的简化方法
* @see 该方法在对请求数据的编码和响应数据的解码时,所采用的字符集均为UTF-8
* @see 该方法会自动对<code>params</code>中的[中文][|][
* ]等特殊字符进行<code>URLEncoder.encode(string,"UTF-8")</code>
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
return sendPostSSLRequest(reqURL, params, null, null);
}
/**
* 发送HTTPS_POST请求
*
* @see 该方法会自动关闭连接,释放资源
* @see 该方法会自动对<code>params</code>中的[中文][|][
* ]等特殊字符进行<code>URLEncoder.encode(string,encodeCharset)</code>
* @param reqURL
* 请求地址
* @param params
* 请求参数
* @param encodeCharset
* 编码字符集,编码请求数据时用之,其为null时默认采用UTF-8解码
* @param decodeCharset
* 解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码
* @return 远程主机响应正文
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static String sendPostSSLRequest(String reqURL, Map<String, String> params, String encodeCharset,
String decodeCharset) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
String responseContent = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
X509TrustManager xtm = 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;
}
};
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { xtm }, null);
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));
HttpPost httpPost = new HttpPost(reqURL);
//设置超时
setTimeout(httpPost);
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, encodeCharset == null ? "UTF-8" : encodeCharset));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
responseContent = EntityUtils.toString(entity, decodeCharset == null ? "UTF-8" : decodeCharset);
EntityUtils.consume(entity);
}
} finally {
httpClient.close();
}
return responseContent;
}
/**
* 发送HTTP_POST请求
*
* @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL
* 请求地址
* @param params
* 发送到远程主机的正文数据,其数据类型为<code>java.util.Map<String, String></code>
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
* 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
* @throws IOException
* @throws Exception
*/
public static String sendPostRequestByJava(String reqURL, Map<String, String> params) throws IOException {
StringBuilder sendData = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sendData.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
if (sendData.length() > 0) {
sendData.setLength(sendData.length() - 1); // 删除最后一个&符号
}
return sendPostRequestByJava(reqURL, sendData.toString());
}
/**
* 发送HTTP_POST请求
*
* @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code>
* @see 本方法默认的连接超时时间为30秒,默认的读取超时时间为30秒
* @param reqURL
* 请求地址
* @param sendData
* 发送到远程主机的正文数据
* @return 远程主机响应正文`HTTP状态码,如<code>"SUCCESS`200"</code><br>
* 若通信过程中发生异常则返回"Failed`HTTP状态码",如<code>"Failed`500"</code>
* @throws IOException
*/
public static String sendPostRequestByJava(String reqURL, String sendData) throws IOException {
HttpURLConnection httpURLConnection = null;
OutputStream out = null; // 写
InputStream in = null; // 读
int httpStatusCode = 0; // 远程主机响应的HTTP状态码
try {
URL sendUrl = new URL(reqURL);
httpURLConnection = (HttpURLConnection) sendUrl.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); // 指示应用程序要将数据写入URL连接,其值默认为false
httpURLConnection.setUseCaches(false);
httpURLConnection.setConnectTimeout(60000); // 60秒连接超时
httpURLConnection.setReadTimeout(60000); // 60秒读取超时
out = httpURLConnection.getOutputStream();
out.write(sendData.toString().getBytes());
// 清空缓冲区,发送数据
out.flush();
// 获取HTTP状态码
httpStatusCode = httpURLConnection.getResponseCode();
in = httpURLConnection.getInputStream();
byte[] byteDatas = new byte[in.available()];
in.read(byteDatas);
return new String(byteDatas) + "`" + httpStatusCode;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
logger.debug("关闭输出流时发生异常,堆栈信息如下", e);
}
}
if (in != null) {
try {
in.close();
} catch (Exception e) {
logger.debug("关闭输入流时发生异常,堆栈信息如下", e);
}
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
httpURLConnection = null;
}
}
}
/**
* https posp请求,可以绕过证书校验
*
* @param url
* @param params
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws ClientProtocolException
*/
public static final String sendHttpsRequestByPost(String url, Map<String, String> params) throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
String responseContent = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建TrustManager
X509TrustManager xtm = 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;
}
};
// 这个好像是HOST验证
X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
public void verify(String arg0, SSLSocket arg1) throws IOException {
}
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
}
public void verify(String arg0, X509Certificate arg1) throws SSLException {
}
};
try {
// TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
ctx.init(null, new TrustManager[] { xtm }, null);
// 创建SSLSocketFactory
SSLSocketFactory socketFactory = new SSLSocketFactory(ctx);
socketFactory.setHostnameVerifier(hostnameVerifier);
// 通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上
httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", socketFactory, 443));
HttpPost httpPost = new HttpPost(url);
//设置超时
setTimeout(httpPost);
List<NameValuePair> formParams = new ArrayList<NameValuePair>(); // 构建POST请求的表单参数
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity(); // 获取响应实体
if (entity != null) {
responseContent = EntityUtils.toString(entity, "UTF-8");
}
} finally {
// 关闭连接,释放资源
try {
httpClient.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return responseContent;
}
/**
* 发送HTTP_POST请求,json格式数据
*
* @param url
* @param body
* @return
* @throws IOException
* @throws ClientProtocolException
* @throws Exception
*/
public static String sendPostByJson(String url, String body) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.custom().build();
HttpPost post = null;
String resData = null;
CloseableHttpResponse result = null;
try {
post = new HttpPost(url);
//设置超时
setTimeout(post);
HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);
post.setConfig(RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
post.setHeader("Content-Type", "application/json");
post.setEntity(entity2);
result = httpclient.execute(post);
if (HttpStatus.SC_OK == result.getStatusLine().getStatusCode()) {
resData = EntityUtils.toString(result.getEntity());
}
} finally {
if (result != null) {
result.close();
}
if (post != null) {
post.releaseConnection();
}
httpclient.close();
}
return resData;
}
}
00037-java 的http请求工具类,HttpClientUtils
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
*/
public class HttpClientUtils {
private static Log logger = LogFactory.getLog(HttpClientUtils.class);
private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
private static CloseableHttpClient httpClient = null;
private static final int DEFAULT_MAX_TOTAL_CONNECTION = 1024;
private static final int DEFAULT_MAX_PER_ROUTE = 300;
private static final String DEFAULT_ENCODING = "UTF-8"; // 默认的查询参数及返回结果的字符串编码
private static final String CONTENT_TYPE_TEXT_XML = "application/xml"; // 默认的查询参数及返回结果的字符串编码
private static final String APPLICATION_XML = "text/xml"; // 默认的查询参数及返回结果的字符串编码
private static final int DEFAULT_CONNECTION_TIME_OUT = 60000; // 默认连接超时时间,
// 60秒
private static final int DEFAULT_READ_TIME_OUT = 200000; // 默认响应超时时间, 60秒
public static JSONObject custRespHeader = new JSONObject();
static {
poolingHttpClientConnectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTION);
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
}
private HttpClientUtils() {
}
/**
* @param url
* @param params
* @param encode
* @param connectTimeout
* @param readTimeout
* @return
*/
public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout,
int readTimeout) {
if (connectTimeout <= 0) {
return null;
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
String responseString;
String requestUrl;
try {
requestUrl = buildRequestUrl(url, params);
} catch (UnsupportedEncodingException e) {
logger.error("encode http get params error, params is " + params, e);
return "";
}
HttpPost httpGet = new HttpPost(requestUrl);
httpGet.setHeader("Connection", "close");
httpGet.setConfig(requestConfig);
responseString = doRequest(httpGet, encode);
return responseString;
}
/**
* @param requestUrl
* @param params
* @return
*/
public static String invokePost(String requestUrl, Map<String, Object> params) {
return invokePost(requestUrl, params, null, null, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT,
DEFAULT_READ_TIME_OUT);
}
public static String invokePost(String requestUrl, Map<String, Object> params,Map<String, String> requestHeader) {
return invokePost(requestUrl, params, requestHeader, null, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT,
DEFAULT_READ_TIME_OUT);
}
/**
* @param requestUrl
* @param requestHeader
* @param requestBody
* @return
*/
public static String invokePost(String requestUrl, Map<String, String> requestHeader, String requestBody) {
return invokePost(requestUrl, null, requestHeader, requestBody, DEFAULT_ENCODING, DEFAULT_CONNECTION_TIME_OUT,
DEFAULT_READ_TIME_OUT);
}
/**
* @param requestUrl
* @param params
* @param requestHeader
* @param requestBody
* @param encode
* @param connectTimeout
* @param readTimeout
* @return
*/
public static String invokePost(String requestUrl, Map<String, Object> params, Map<String, String> requestHeader,
String requestBody, String encode, int connectTimeout, int readTimeout) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeout)
.setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectTimeout).build();
String responseString;
HttpPost httpPost = new HttpPost(requestUrl);
httpPost.setConfig(requestConfig);
if (MapUtils.isNotEmpty(requestHeader)) {
for (Map.Entry<String, String> entry : requestHeader.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
buildPostParams(httpPost, params, requestBody, encode);
responseString = doRequest(httpPost, encode);
return responseString;
}
/**
* @param httpPost
* @param params
* @param requestBody
* @param encode
*/
private static void buildPostParams(HttpPost httpPost, Map<String, Object> params, String requestBody,
String encode) {
try {
if (MapUtils.isNotEmpty(params)) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
String value = null;
if (entry.getValue() instanceof String) {
value = (String) entry.getValue();
} else {
value = JSON.toJSONString(entry.getValue());
}
nameValuePairs.add(new BasicNameValuePair(entry.getKey(), value));
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, encode));
}
if (StringUtils.isNotBlank(requestBody)) {
httpPost.setEntity(new StringEntity(requestBody, encode));
}
} catch (UnsupportedEncodingException e) {
logger.error("HttpClientUtils.buildPostParams error, params = " + params, e);
}
}
/**
* @param httpRequestBase
* @param encode
* @return
*/
private static String doRequest(HttpRequestBase httpRequestBase, String encode) {
String responseString = null;
try {
long start = System.currentTimeMillis();
CloseableHttpResponse response = httpClient.execute(httpRequestBase);
logger.info("HttpClientUtils Begin Invoke: " + httpRequestBase.getURI() + ", cost time "
+ (System.currentTimeMillis() - start) + " ms");
try {
Header[] headers = response.getHeaders("isLogin");
if(headers!=null && headers.length>0){
custRespHeader.put(headers[0].getName(),headers[0].getValue());
}
HttpEntity entity = response.getEntity();
try {
if (entity != null) {
responseString = EntityUtils.toString(entity, encode);
}
} finally {
if (entity != null) {
entity.getContent().close();
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error(String.format("[HttpClientUtils.doRequest] get response error, url:%s",
httpRequestBase.getURI()), e);
responseString = "";
} finally {
if (response != null) {
response.close();
}
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
logger.error(String.format("[HttpClientUtils.doRequest] invoke get timout error, url:%s",
httpRequestBase.getURI()), e);
responseString = "";
} catch (Exception e) {
e.printStackTrace();
logger.error(
String.format("[HttpClientUtils.doRequest] invoke get error, url:%s", httpRequestBase.getURI()), e);
responseString = "";
} finally {
httpRequestBase.releaseConnection();
}
logger.info("HttpClientUtils response : " + responseString);
return responseString;
}
/**
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
private static String buildRequestUrl(String url, Map<String, String> params) throws UnsupportedEncodingException {
if (CollectionUtils.isEmpty(params)) {
return url;
}
StringBuilder requestUrl = new StringBuilder();
requestUrl.append(url);
int i = 0;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (i == 0) {
requestUrl.append("?");
}
requestUrl.append(entry.getKey());
requestUrl.append("=");
String value = entry.getValue();
requestUrl.append(URLEncoder.encode(value, "UTF-8"));
requestUrl.append("&");
i++;
}
requestUrl.deleteCharAt(requestUrl.length() - 1);
return requestUrl.toString();
}
public static void setStringParams(HttpPost httpost,
Map<String, String> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key).toString()));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
}
}
/**
* @param httpRequest
* @param entity
* @param
* @return
*/
private static String sendRequest(HttpRequestBase httpRequest, HttpEntity entity) {
httpRequest.setHeader("User-Agent", "okHttp");
if (httpRequest instanceof HttpEntityEnclosingRequestBase) {
// checkArgument(null!=entity,"HttpEntity请求体不能为空");
((HttpEntityEnclosingRequestBase) httpRequest).setEntity(entity);
}
//忽略证书
SSLContext sslContext = SSLContexts.createDefault();
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
try {
sslContext.init(null, new TrustManager[]{tm}, null);
} catch (Exception ex) {
ex.printStackTrace();
}
X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslsf)
.build();
HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
CloseableHttpResponse response = null;
String resString = null;
try {
response = httpClient.execute(httpRequest);
HttpEntity resEntity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
resString = EntityUtils.toString(resEntity, "UTF-8");
System.err.println(statusCode);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("响应码状态不是200");
}
return resString;
} catch (Exception e) {
throw new RuntimeException(resString, e);
} finally {
try {
if (response != null) {
response.close();
}
if (httpRequest != null) {
httpRequest.releaseConnection();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
调用示例:
public static void delAll(){
String url = path+"test/test/deleteAll";
Map map = new HashMap<>();
String str = HttpClientUtils.invokePost(url,map);
System.out.println("delAll.str="+str);
}
C#操作HttpClient工具类库
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using Newtonsoft.Json;
namespace Dcflow
{
public class HttpHelper
{
//获取Configuration对象
public static string DCFLOW_ZUUL = ConfigurationManager.AppSettings["SERVER_URL"];
//token键
public static string ACCESS_TOKEN_KEY = "";
//token值
public static string ACCESS_TOKEN_VALUE = "";
private static Dictionary<string, string> headers;
public static Dictionary<string, string> Headers { get => headers; set => headers = value; }
private static readonly HttpClient _httpClient;
static HttpHelper()
{
try
{
//HttpClient热身
_httpClient = new HttpClient() { BaseAddress = new Uri(DCFLOW_ZUUL) };
_httpClient.DefaultRequestHeaders.Connection.Add("keep-alive");
_httpClient.SendAsync(new HttpRequestMessage
{
Method = new HttpMethod("HEAD"),
RequestUri = new Uri(DCFLOW_ZUUL + "/")
}).Result.EnsureSuccessStatusCode();
}
catch (Exception)
{
}
}
public static String httpGet(string url)
{
if (HttpHelper.headers != null)
{
_httpClient.DefaultRequestHeaders.Clear();
headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;
// 设置请求头
foreach (KeyValuePair<string, string> item in headers)
{
_httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var data = "";
try
{
// response
var response = _httpClient.GetAsync(new Uri(DCFLOW_ZUUL + url)).Result;
data = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
MessageBox.Show("HTTP GET请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;//接口调用成功获取的数据
}
public static String httpPost(string url, Dictionary<string, string> param, string dataType)
{
if (HttpHelper.headers != null)
{
_httpClient.DefaultRequestHeaders.Clear();
headers[ACCESS_TOKEN_KEY] = HttpHelper.ACCESS_TOKEN_VALUE;
//设置请求头
foreach (KeyValuePair<string, string> item in headers)
{
_httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
}
}
var data = "";
try
{
ByteArrayContent content = null;
if (dataType.ToLower().Equals("json"))
{
content = new StringContent(JsonConvert.SerializeObject(param));
//设置Http的内容标头
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
}
else
{
content = new FormUrlEncodedContent(param);
}
// response
var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;
data = response.Content.ReadAsStringAsync().Result;
}
catch (Exception e)
{
MessageBox.Show("HTTP POST请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;//接口调用成功数据
}
public static String httpUploadAsync(string url, List<string> filePath)
{
var data = "";
try
{
using (var content = new MultipartFormDataContent())
{
for (int i = 0; i < filePath.Count; i++)
{
FileStream fs = File.OpenRead(filePath[i]);
var streamContent = new StreamContent(fs);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
content.Add(imageContent, "upfile", Path.GetFileName(filePath[i]));
fs.Close();
}
// response
var response = _httpClient.PostAsync(DCFLOW_ZUUL + url, content).Result;
data = response.Content.ReadAsStringAsync().Result;
};
}
catch (Exception e)
{
MessageBox.Show("HTTP POST MultipartFormData 请求失败,请检查网络或联系管理员查看服务器状态,错误消息:" + e.Message);
//throw;
}
return data;
}
}
}
本文分享自微信公众号 - IT技术分享社区(gh_a27c0758eb03)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
coding++ :HttpClientUtils 封装
1、关键 JAR
<!--
《《===================》》
httpClient
《《===================》》
-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--
《《===================》》
IO
《《===================》》
-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、封装工具类(HttpClientUtils)


//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.tree.ztree_demo.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @Description:HttpClientUtils 封装
* @author: MLQ
* @param:
* @return:
* @exception:
* @date: 2019/5/17 15:57
*/
public class HttpClientUtils {
private static Logger LOG = LoggerFactory.getLogger(HttpClientUtils.class);
private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
private static RequestConfig requestConfig;
private static final int MAX_TOTAL = 100;
private static final int MAX_TIMEOUT = 7000;
private static final int CONNECT_TIMEOUT = 10000;
private static final int SOCKET_TIMEOUT = 40000;
private static final String CHARSET = "UTF-8";
public HttpClientUtils() {
}
public static String doGet(String url) throws Exception {
return doGet(url, new HashMap());
}
public static String doGet(String url, Map<String, Object> params) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doGet url is null or '''' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var4 = params.entrySet().iterator();
while(var4.hasNext()) {
Entry<String, Object> entry = (Entry)var4.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
CloseableHttpResponse response = null;
InputStream instream = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
URIBuilder URIBuilder = new URIBuilder(url);
URIBuilder.addParameters(pairList);
URI uri = URIBuilder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doGet statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var16) {
LOG.error("doGet IO ERROR :{}", var16.getMessage());
} catch (URISyntaxException var17) {
LOG.error("doGet URISyntaxException :{}", var17.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpclient) {
httpclient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return result;
}
}
public static String doGet(String url, Map<String, Object> params, String charset) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doGet url is null or '''' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var5 = params.entrySet().iterator();
while(var5.hasNext()) {
Entry<String, Object> entry = (Entry)var5.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
CloseableHttpResponse response = null;
InputStream instream = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
URIBuilder URIBuilder = new URIBuilder(url);
URIBuilder.addParameters(pairList);
URI uri = URIBuilder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doGet statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, charset);
}
} catch (IOException var17) {
LOG.error("doGet IO ERROR :{}", var17.getMessage());
} catch (URISyntaxException var18) {
LOG.error("doGet URISyntaxException :{}", var18.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpclient) {
httpclient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return result;
}
}
public static String doPost(String apiUrl) throws Exception {
return doPost(apiUrl, (Map)(new HashMap()));
}
public static String doPost(String url, Map<String, Object> params) throws Exception {
String result = null;
String param = "";
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '''' ");
return result;
} else {
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var5 = params.entrySet().iterator();
while(var5.hasNext()) {
Entry<String, Object> entry = (Entry)var5.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
if (param.equals("")) {
param = (String)entry.getKey() + "=" + entry.getValue();
} else {
param = param + "&" + (String)entry.getKey() + "=" + entry.getValue();
}
}
LOG.info("http请求地址:" + url + "?" + param);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
LOG.info("doPost Result:{}", result);
}
} catch (IOException var14) {
LOG.error("doPost ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return result;
}
}
public static String doPost(String url, String xml) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPost url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
LOG.info("短信请求服务器地址:" + url + "?" + xml);
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(xml, "GBK"));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var12) {
LOG.error("doPost ERROR :{}", var12.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return result;
}
}
public static String doPost(String url, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var13) {
LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return result;
}
}
public static String doPostPay(String url, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var13) {
LOG.error("doPost BY JSON ERROR :{}", var13.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return result;
}
}
public static String doPostSSL(String apiUrl, Map<String, Object> params) throws Exception {
String result = null;
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
List<NameValuePair> pairList = new ArrayList(params.size());
Iterator var8 = params.entrySet().iterator();
Entry entry;
while(var8.hasNext()) {
entry = (Entry)var8.next();
NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
pairList.add(pair);
}
httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
LOG.info("doPostSSL statusCode:{}", statusCode);
entry = null;
return String.valueOf(entry);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (Exception var14) {
LOG.error("doPostSSL ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return result;
}
}
public static String doPostSSL(String apiUrl, Object json) throws Exception {
String result = null;
if (StringUtils.isEmpty(apiUrl)) {
LOG.info("warn:doPostSSL By Json url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
InputStream instream = null;
HttpEntity entity;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
return result;
}
LOG.info("doPostSSL by json statusCode:{}", statusCode);
entity = null;
} catch (Exception var13) {
LOG.error("doPostSSL BY JSON ERROR :{}", var13.getMessage());
return result;
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
LOG.info("close instream response httpClient connection succ");
}
return String.valueOf(entity);
}
}
private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
SSLConnectionSocketFactory sslsf = null;
try {
SSLContext sslContext = (new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
public void verify(String host, SSLSocket ssl) throws IOException {
}
public void verify(String host, X509Certificate cert) throws SSLException {
}
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
});
} catch (GeneralSecurityException var2) {
LOG.error("createSSLConnSocketFactory ERROR :{}", var2.getMessage());
}
return sslsf;
}
public static String doPostPay(String url, Object json, String authorization) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("warn:doPostByJson url is null or '''' ");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", authorization);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("doPost statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var14) {
LOG.error("doPost BY JSON ERROR :{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return result;
}
}
public static String doPostPayUpgraded(String url, Object json, String authorization) throws Exception {
String result = null;
if (StringUtils.isEmpty(url)) {
LOG.info("新支付接口url不能为空!");
return result;
} else {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null;
InputStream instream = null;
try {
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("Authorization", authorization);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
LOG.info("新支付请求状态 statusCode:{}", statusCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
instream = entity.getContent();
result = IOUtils.toString(instream, "UTF-8");
}
} catch (IOException var14) {
LOG.error("新支付接口发送异常:{}", var14.getMessage());
} finally {
if (null != instream) {
instream.close();
}
if (null != response) {
response.close();
}
if (null != httpClient) {
httpClient.close();
}
}
return result;
}
}
static {
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(100);
Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(10000);
configBuilder.setSocketTimeout(40000);
configBuilder.setConnectionRequestTimeout(7000);
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
}
}
直接拷贝就可以使用了。
httpClient 3.1 工具类
1. maven 依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
2. 工具类代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClientUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
public static String getResFromGetRequestUrl(String url) {
String res = HttpClientUtils.doGet(url, null, "UTF-8", false);
return res;
}
public static String doGet(String url, String queryString, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(url);
try {
if (StringUtils.isNotBlank(queryString))
// 对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串
method.setQueryString(URIUtil.encodeQuery(queryString));
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (URIException e) {
logger.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
} catch (IOException e) {
logger.error("执行HTTP Get请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
/**
* 执行一个HTTP POST请求,返回请求响应的HTML
*
* @param url 请求的URL地址
* @param params 请求的查询参数,可以为null
* @param charset 字符集
* @param pretty 是否美化
* @return 返回请求响应的HTML
*/
public static String doPost(String url, Map<String, String> params, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//设置参数的字符集
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,charset);
//设置Http Post数据
if (params != null) {
//HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
//p.setParameter(entry.getKey(), entry.getValue());
method.setParameter(entry.getKey(), entry.getValue());
}
//method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
String line;
while ((line = reader.readLine()) != null) {
if (pretty)
response.append(line).append(System.getProperty("line.separator"));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
} finally {
method.releaseConnection();
}
return response.toString();
}
}
今天关于HttpClientUtil 工具类和http工具包的分享就到这里,希望大家有所收获,若想了解更多关于00037-java 的http请求工具类,HttpClientUtils、C#操作HttpClient工具类库、coding++ :HttpClientUtils 封装、httpClient 3.1 工具类等相关知识,可以在本站进行查询。
本文标签: