HttpHandler
public interface HttpHandler {
HttpResponse get(String var1, HttpRequest var2);
HttpResponse post(String var1, HttpRequest var2);
}
HttpHandlerImpl
public class HttpHandlerImpl implements HttpHandler {
private static final Logger log = LoggerFactory.getLogger(HttpHandlerImpl.class);
private int defaultMaxPerRoute = 100;
private int defaultMaxTotal = 600;
private HttpClientBuilder syncHc;
private CloseableHttpClient httpClient;
private PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager();
private PoolingClientConnectionManager syncHttpsConnectionManager;
private DefaultHttpClient syncHttpsHc;
public HttpHandlerImpl() throws Exception {
this.syncConnectionManager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);
this.syncConnectionManager.setMaxTotal(this.defaultMaxTotal);
this.httpClient = HttpClientBuilder.create().setConnectionManager(this.syncConnectionManager).build();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load((InputStream)null, (char[])null);
SSLSocketFactoryEx sf = new SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
BasicHttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
this.syncHttpsConnectionManager = new PoolingClientConnectionManager(registry);
this.syncHttpsConnectionManager.setDefaultMaxPerRoute(this.defaultMaxPerRoute);
this.syncHttpsConnectionManager.setMaxTotal(this.defaultMaxTotal);
this.syncHttpsHc = new DefaultHttpClient(this.syncHttpsConnectionManager, params);
}
public HttpResponse get(String url, HttpRequest request) {
RequestBuilder builder = this.getRequestBuilder(url, request);
return this.executeHttp(url, request, builder);
}
private RequestBuilder getRequestBuilder(String url, HttpRequest request) {
RequestBuilder builder = RequestBuilder.get(url);
Iterator i$ = request.getQueryParamPairs().iterator();
while(i$.hasNext()) {
NameValuePair s = (NameValuePair)i$.next();
builder.addParameter(s.getName(), s.getValue());
}
i$ = request.getHeaders().entrySet().iterator();
while(i$.hasNext()) {
Entry s1 = (Entry)i$.next();
builder.addHeader((String)s1.getKey(), s1.getValue().toString());
}
return builder;
}
private HttpResponse parseHttpResponse(HttpRequest request, CloseableHttpResponse execute) throws IOException {
HttpResponse response = new HttpResponse();
response.setStatus(execute.getStatusLine().getStatusCode());
String encode = "utf-8";
if(request.getAsStringEncoding() != null) {
encode = request.getAsStringEncoding();
}
if(StringUtils.isBlank(request.getAs())) {
response.setBody(EntityUtils.toString(execute.getEntity(), encode));
} else if(StringUtils.equals(request.getAs(), HttpRequest.AS_STRING)) {
response.setBody(EntityUtils.toString(execute.getEntity(), encode));
} else if(StringUtils.equals(request.getAs(), HttpRequest.AS_BYTEARRAY)) {
response.setBody(EntityUtils.toByteArray(execute.getEntity()));
} else if(StringUtils.equals(request.getAs(), HttpRequest.AS_JSON)) {
response.setBody(JSON.parseObject(EntityUtils.toString(execute.getEntity())));
} else {
if(!StringUtils.equals(request.getAs(), HttpRequest.AS_AES_STRING)) {
throw new UafException("HttpRequest unknow As type");
}
response.setBody(AESCodec.decrypt(EntityUtils.toString(execute.getEntity()), request.getAesToken()));
}
return response;
}
public HttpResponse post(String url, HttpRequest request) {
RequestBuilder builder = this.postRequestBuilder(url, request);
return this.executeHttp(url, request, builder);
}
private HttpResponse executeHttp(String url, HttpRequest request, RequestBuilder builder) {
Builder requestConfigBuilder = RequestConfig.custom().setConnectTimeout(request.getConnTimeout()).setSocketTimeout(request.getSocketTimeout());
if(request.isProxy()) {
requestConfigBuilder.setProxy(new HttpHost(request.getProxyIp(), request.getProxyPort(), request.getProxySchemaName()));
}
builder.setConfig(requestConfigBuilder.build());
CloseableHttpResponse execute = null;
HttpResponse response = null;
Exception ex = null;
HttpResponse var20;
try {
HttpUriRequest e = builder.build();
if(StringUtils.isNotBlank(request.getUserName())) {
UsernamePasswordCredentials headers = new UsernamePasswordCredentials(request.getUserName(), request.getPassword());
e.addHeader((new BasicScheme()).authenticate(headers, e, new BasicHttpContext()));
}
if(request.isUseHttps()) {
execute = this.syncHttpsHc.execute(e);
} else {
execute = this.httpClient.execute(e);
}
Header[] var19 = execute.getHeaders("Content-Encoding");
if(var19 != null) {
Header[] arr$ = var19;
int len$ = var19.length;
for(int i$ = 0; i$ < len$; ++i$) {
Header header = arr$[i$];
if("gzip".equalsIgnoreCase(header.getValue())) {
execute.setEntity(new GzipDecompressingEntity(execute.getEntity()));
}
}
}
response = this.parseHttpResponse(request, execute);
var20 = response;
} catch (Exception var17) {
ex = var17;
if(ExceptionUtil.isHttpConnectTimeOut(var17)) {
throw new ConnectionException(url, var17);
}
if(ExceptionUtil.isHttpReadTimeOut(var17)) {
throw new TimeoutException(url, var17);
}
throw new UafException(url, var17);
} finally {
request.setUrl(url);
if(response != null && response.getStatus() == 200) {
GlobalInfo.setExtenal(request, response.getBody(), (Exception)null);
} else {
GlobalInfo.setExtenal(request, response, ex);
}
}
return var20;
}
private RequestBuilder postRequestBuilder(String url, HttpRequest request) {
try {
RequestBuilder e = RequestBuilder.post(url);
Iterator data = request.getHeaders().entrySet().iterator();
while(data.hasNext()) {
Entry s = (Entry)data.next();
e.addHeader((String)s.getKey(), s.getValue().toString());
}
if(request.getBody() != null) {
if(request.getBody() instanceof String) {
if(request.getBodyContentType() != null) {
e.setEntity(new StringEntity((String)request.getBody(), request.getBodyContentType()));
} else {
e.setEntity(new StringEntity((String)request.getBody()));
}
} else if(request.getBody() instanceof byte[]) {
e.setEntity(new ByteArrayEntity((byte[])((byte[])request.getBody())));
}
} else {
ArrayList data1 = new ArrayList();
data1.addAll(request.getFormParamPairs());
e.setEntity(new UrlEncodedFormEntity(data1, "UTF-8"));
}
return e;
} catch (Exception var6) {
throw new RuntimeException(var6);
}
}
}
HttpRequest
public class HttpRequest {
public static String AS_STRING = "string";
public static String AS_BYTEARRAY = "byteArray";
public static String AS_JSON = "json";
public static String AS_AES_STRING = "AES";
private String as;
private String asStringEncoding;
private String aesToken;
private List queryParamPairs = new ArrayList();
private List formParamPairs = new ArrayList();
private Map headers = new HashMap();
private int socketTimeout = 5000;
private int connTimeout = 30000;
private String method;
private Object body;
private ContentType bodyContentType;
private String contentType;
private boolean isUseHttps;
private String url;
private boolean isProxy = false;
private String proxyIp;
private int proxyPort = 0;
private String proxySchemaName = "http";
private String userName;
private String password;
HttpRequest() {
}
public void setContentType(String type) {
this.headers.put("Content-Type", type);
}
public void setAcceptEncoding(String encoding) {
this.headers.put("Accept-Encoding", encoding);
}
public String toString() {
HashMap data = new HashMap();
data.put("connTimeout", Integer.valueOf(this.connTimeout));
data.put("socketTimeout", Integer.valueOf(this.socketTimeout));
if(this.body != null) {
data.put("body", this.body);
}
data.put("userName", this.userName);
data.put("url", this.url);
if(this.isProxy) {
data.put("proxyIp", this.proxyIp);
data.put("proxyPort", Integer.valueOf(this.proxyPort));
}
ArrayList params = new ArrayList();
params.addAll(this.queryParamPairs);
params.addAll(this.formParamPairs);
if(!params.isEmpty()) {
data.put("params", params);
}
if(this.headers.isEmpty()) {
;
}
return JSON.toJSONString(data);
}
public String getAs() {
return this.as;
}
public String getAsStringEncoding() {
return this.asStringEncoding;
}
public String getAesToken() {
return this.aesToken;
}
public List getQueryParamPairs() {
return this.queryParamPairs;
}
public List getFormParamPairs() {
return this.formParamPairs;
}
public Map getHeaders() {
return this.headers;
}
public int getSocketTimeout() {
return this.socketTimeout;
}
public int getConnTimeout() {
return this.connTimeout;
}
public String getMethod() {
return this.method;
}
public Object getBody() {
return this.body;
}
public ContentType getBodyContentType() {
return this.bodyContentType;
}
public String getContentType() {
return this.contentType;
}
public boolean isUseHttps() {
return this.isUseHttps;
}
public String getUrl() {
return this.url;
}
public boolean isProxy() {
return this.isProxy;
}
public String getProxyIp() {
return this.proxyIp;
}
public int getProxyPort() {
return this.proxyPort;
}
public String getProxySchemaName() {
return this.proxySchemaName;
}
public String getUserName() {
return this.userName;
}
public String getPassword() {
return this.password;
}
public void setAs(String as) {
this.as = as;
}
public void setAsStringEncoding(String asStringEncoding) {
this.asStringEncoding = asStringEncoding;
}
public void setAesToken(String aesToken) {
this.aesToken = aesToken;
}
public void setQueryParamPairs(List queryParamPairs) {
this.queryParamPairs = queryParamPairs;
}
public void setFormParamPairs(List formParamPairs) {
this.formParamPairs = formParamPairs;
}
public void setHeaders(Map headers) {
this.headers = headers;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public void setConnTimeout(int connTimeout) {
this.connTimeout = connTimeout;
}
public void setMethod(String method) {
this.method = method;
}
public void setBody(Object body) {
this.body = body;
}
public void setBodyContentType(ContentType bodyContentType) {
this.bodyContentType = bodyContentType;
}
public void setUseHttps(boolean isUseHttps) {
this.isUseHttps = isUseHttps;
}
public void setUrl(String url) {
this.url = url;
}
public void setProxy(boolean isProxy) {
this.isProxy = isProxy;
}
public void setProxyIp(String proxyIp) {
this.proxyIp = proxyIp;
}
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
public void setProxySchemaName(String proxySchemaName) {
this.proxySchemaName = proxySchemaName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
}
HttpRequestBuilder
public class HttpRequestBuilder {
private HttpRequest request = new HttpRequest();
private HttpRequestBuilder() {
}
public static HttpRequestBuilder newGetHttpRequestBuilder() {
HttpRequestBuilder builder = new HttpRequestBuilder();
builder.request.setMethod("GET");
return builder;
}
public static HttpRequestBuilder newPostHttpRequestBuilder() {
HttpRequestBuilder builder = new HttpRequestBuilder();
builder.request.setMethod("POST");
return builder;
}
public HttpRequestBuilder addQueryParam(String name, Object value) {
if(value != null) {
this.request.getQueryParamPairs().add(new BasicNameValuePair(name, value.toString()));
}
return this;
}
public HttpRequestBuilder addFormParam(String name, Object value) {
if(value != null) {
this.request.getFormParamPairs().add(new BasicNameValuePair(name, value.toString()));
}
return this;
}
public HttpRequestBuilder addHeader(String name, Object value) {
this.request.getHeaders().put(name, value);
return this;
}
public HttpRequestBuilder withContentType(String type) {
this.addHeader("Content-Type", type);
return this;
}
public HttpRequestBuilder withAcceptEncoding(String type) {
this.addHeader("Accept-Encoding", type);
return this;
}
public HttpRequestBuilder withStringBody(String body) {
this.request.setBody(body);
return this;
}
public HttpRequestBuilder withStringBody(String body, ContentType contentType) {
this.request.setBody(body);
this.request.setBodyContentType(contentType);
return this;
}
public HttpRequestBuilder withByteArrayBody(byte[] body) {
this.request.setBody(body);
return this;
}
public HttpRequestBuilder withTimeout(int socketTimeout, int connTimeout) {
this.request.setConnTimeout(connTimeout);
this.request.setSocketTimeout(socketTimeout);
return this;
}
public HttpRequestBuilder withResponseAs(String type) {
this.request.setAs(type);
return this;
}
public HttpRequestBuilder withAesToken(String token) {
this.request.setAesToken(token);
return this;
}
public HttpRequestBuilder useHttps() {
this.request.setUseHttps(true);
return this;
}
public HttpRequestBuilder withProxy(String ip, int port) {
this.request.setProxy(true);
this.request.setProxyIp(ip);
this.request.setProxyPort(port);
return this;
}
public HttpRequestBuilder addUserInfo(String userName, String password) {
this.request.setUserName(userName);
this.request.setPassword(password);
return this;
}
public HttpRequest build() {
return this.request;
}
}
HttpResponse
public class HttpResponse {
private Object body;
private int status;
private Map headers;
public HttpResponse() {
}
public Object getBody() {
return this.body;
}
public int getStatus() {
return this.status;
}
public Map getHeaders() {
return this.headers;
}
public void setBody(Object body) {
this.body = body;
}
public void setStatus(int status) {
this.status = status;
}
public void setHeaders(Map headers) {
this.headers = headers;
}
}
SSLSocketFactoryEx
public class SSLSocketFactoryEx extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
this.sslContext.init((KeyManager[])null, new TrustManager[]{tm}, (SecureRandom)null);
}
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
Socket _socket = this.sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
LinkedList limited = new LinkedList();
String[] arr$ = ((SSLSocket)_socket).getEnabledCipherSuites();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String suite = arr$[i$];
if(!suite.contains("_DHE_")) {
limited.add(suite);
}
}
((SSLSocket)_socket).setEnabledCipherSuites((String[])limited.toArray(new String[limited.size()]));
return _socket;
}
public Socket createSocket() throws IOException {
Socket socket = this.sslContext.getSocketFactory().createSocket();
LinkedList limited = new LinkedList();
String[] arr$ = ((SSLSocket)socket).getEnabledCipherSuites();
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; ++i$) {
String suite = arr$[i$];
if(!suite.contains("_DHE_")) {
limited.add(suite);
}
}
((SSLSocket)socket).setEnabledCipherSuites((String[])limited.toArray(new String[limited.size()]));
return socket;
}
}
使用示例:
HttpRequestBuilder builder = HttpRequestBuilder.newPostHttpRequestBuilder();
builder.addFormParam("paramName","paramValue"));
builder.withTimeout(readTimeout(),ConnTimeout());
HttpResponse response = httpHandler.post("url",builder.build());
String content=null;
if(null != response.getBody()){
content = StringEscapeUtils.unescapeHtml(response.getBody().toString());
}
return content;