package utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
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;
/**
* <groupId>org.apache.httpcomponents</groupId>
* <artifactId>httpclient</artifactId>
* <version>4.2.6</version>
* 版本不能太高
*/
public class HttpClientUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
public static CookieStore cookieStore;
public HttpClientUtil() {
}
public static Map<String, Object> doPost(String url, Map<String, String> map, String entityKind, String charset) {
SSLClient sslClient = null;
try {
sslClient = new SSLClient();
Thread.sleep(50L);
HttpClientParams.setCookiePolicy(sslClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json,text/plain,*/*");
if (cookieStore != null) {
sslClient.setCookieStore(cookieStore);
}
JSONObject postData = new JSONObject();
if (map != null && !map.isEmpty()) {
List<NameValuePair> list = new ArrayList();
for (Map.Entry<String, String> entry : map.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
postData.put(entry.getKey(), entry.getValue());
}
StringEntity stringEntity = new StringEntity(postData.toString(), "UTF-8");
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, charset);
if ("json".equals(entityKind)) {
httpPost.setEntity(stringEntity);
} else {
httpPost.setEntity(urlEncodedFormEntity);
}
}
HttpResponse response = sslClient.execute(httpPost);
cookieStore = sslClient.getCookieStore();
return solve(response, charset);
} catch (Exception e) {
LOGGER.info("doPost error occur,{}", e);
} finally {
if (sslClient != null) {//主动释放客户端
sslClient.getConnectionManager().shutdown();
}
}
return null;
}
public static Map<String, Object> doGet(String url, Map<String, String> map, String charset) {
try {
Thread.sleep(50L);
URIBuilder builder = new URIBuilder(url);
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.addParameter(entry.getKey(), entry.getValue());
}
}
SSLClient sslClient = new SSLClient();
HttpGet httpGet = new HttpGet(builder.build());
httpGet.setHeader("Accept", "application/json,text/plain,*/*");
if (cookieStore != null) {
sslClient.setCookieStore(cookieStore);
}
HttpResponse response = sslClient.execute(httpGet);
cookieStore = sslClient.getCookieStore();
return solve(response, charset);
} catch (Exception e) {
LOGGER.info("doGet error occur,{}", e);
}
return null;
}
private static Map<String, Object> solve(HttpResponse response, String charset) {
try {
if (response != null) {
if (response.getStatusLine().getStatusCode() == 302) {
String loginUrl = response.getFirstHeader("Location").getValue();
return toMap(response.getStatusLine().getStatusCode(), loginUrl);
}
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
return toMap(response.getStatusLine().getStatusCode(), EntityUtils.toString(resEntity, charset));
}
}
} catch (Exception e) {
LOGGER.info("solve error occur,{}", e);
}
return null;
}
private static Map<String, Object> toMap(Integer code, String msg) {
Map<String, Object> result = new HashMap<>();
result.put("code", code);
result.put("msg", msg);
return result;
}
}
/**
* 跳过https协议的ssl认证
*/
class SSLClient extends DefaultHttpClient {
SSLClient() throws Exception {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = 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;
}
};
ctx.init((KeyManager[]) null, new TrustManager[]{tm}, (SecureRandom) null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}