求一个 httpClient 4.5.x 的工具类,求大佬们赏赐一个!
希望包含上传文件和下载文件的功能,能支持 HTTPS
不做和伸手党,会给分的 😊
下面是按照百度写的代码,感觉有点糟心,提点建议也谢谢了~
package com.fadada.sdk.util.http;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
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.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.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.util.EntityUtils;
public class Zhou {
public static CloseableHttpResponse doGet(String url, String cookie, String refer) throws IOException {
// http实现get请求:首先设置全局的标准cookie策略
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
// 设置可关闭的httpclient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
// 发送get请求
HttpGet get = new HttpGet(url);
if (cookie != null) {
get.setHeader("Cookie", cookie);
}
if (refer != null) {
get.setHeader("Refer", refer);
}
CloseableHttpResponse response = httpClient.execute(get);
return response;
}
public static CloseableHttpResponse doPost(String url, List<NameValuePair> values, String cookie, String refer) throws IOException {
// http实现post请求:首先设置全局的标准cookie策略
RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
// 设置可关闭的httpclient
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
// 对请求参数进行编码后再进行发送
HttpPost post = new HttpPost(url);
if (cookie != null) {
post.setHeader("Cookie", cookie);
}
if (refer != null) {
post.setHeader("Refer", refer);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
post.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(post);
return response;
}
private static TrustManager manager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
private static SSLConnectionSocketFactory socketFactory;// 私密连接工厂
private static void enableSSL() {
// https网站一般情况下使用了安全系数较低的SHA-1签名,因此首先我们在调用SSL之前需要重写验证方法,取消检测SSL。
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { manager }, null);
socketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
public static CloseableHttpResponse doHttpsGet(String url, String cookie, String refer) throws IOException {
enableSSL();
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRequestConfig).build();
// 发送get请求
HttpGet get = new HttpGet(url);
if (cookie != null) {
get.setHeader("Cookie", cookie);
}
if (refer != null) {
get.setHeader("Refer", refer);
}
CloseableHttpResponse response = httpClient.execute(get);
return response;
}
public static CloseableHttpResponse doHttpsPost(String url, List<NameValuePair> values, String cookie, String refer) throws IOException {
enableSSL();
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRequestConfig).build();
// 对请求参数进行编码后再进行发送
HttpPost post = new HttpPost(url);
if (cookie != null) {
post.setHeader("Cookie", cookie);
}
if (refer != null) {
post.setHeader("Refer", refer);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
post.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(post);
return response;
}
public static String doHttpsPost(String url, HttpEntity entity) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
enableSSL();
RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM)).build();
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRequestConfig).build();
// 对请求参数进行编码后再进行发送
HttpPost post = new HttpPost(url);
post.setEntity(entity);
response = httpClient.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity respEntity = response.getEntity();
if (null == entity) {
throw new RuntimeException("HttpEntity is null.");
}
return EntityUtils.toString(respEntity, Consts.UTF_8);
} else {
throw new RuntimeException("connect fail. http_status:" + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally{
try {
// 关闭连接,释放资源
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于