Created
May 4, 2018 10:50
-
-
Save handosme/556039da84c8c0e2b11432d75101e3eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.ihansen.utils.net; | |
import org.apache.http.HttpEntity; | |
import org.apache.http.NameValuePair; | |
import org.apache.http.client.CookieStore; | |
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.HttpUriRequest; | |
import org.apache.http.client.utils.URIBuilder; | |
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.SSLConnectionSocketFactory; | |
import org.apache.http.conn.ssl.TrustStrategy; | |
import org.apache.http.entity.ContentType; | |
import org.apache.http.entity.mime.HttpMultipartMode; | |
import org.apache.http.entity.mime.MultipartEntityBuilder; | |
import org.apache.http.entity.mime.content.FileBody; | |
import org.apache.http.entity.mime.content.StringBody; | |
import org.apache.http.impl.client.BasicCookieStore; | |
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.ssl.SSLContextBuilder; | |
import org.apache.http.util.EntityUtils; | |
import org.ihansen.utils.Const; | |
import org.ihansen.utils.Utils; | |
import javax.net.ssl.*; | |
import javax.servlet.http.HttpServletRequest; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.UnsupportedEncodingException; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.nio.charset.Charset; | |
import java.security.SecureRandom; | |
import java.security.cert.CertificateException; | |
import java.security.cert.X509Certificate; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Map; | |
public class HttpUtil { | |
private static final CloseableHttpClient CLIENT = getUnCheckSSLHttpClient(); | |
private static final CookieStore cookieStore = new BasicCookieStore(); | |
static { | |
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { | |
@Override | |
public void run() { | |
Utils.closeQuiet(CLIENT); | |
} | |
})); | |
} | |
/** | |
* 实例化一个{@link CloseableHttpClient} | |
* | |
* @return | |
*/ | |
public static CloseableHttpClient getUnCheckSSLHttpClient() { | |
try { | |
SSLContext sslContext = SSLContext.getInstance("SSL"); | |
sslContext.init(null, new TrustManager[]{new X509TrustManager() { | |
@Override | |
public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) | |
throws CertificateException { | |
} | |
@Override | |
public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) | |
throws CertificateException { | |
} | |
@Override | |
public X509Certificate[] getAcceptedIssuers() { | |
return null; | |
} | |
}}, new SecureRandom()); | |
HostnameVerifier verifier = new HostnameVerifier() { | |
public boolean verify(String hostname, SSLSession session) { | |
return true; | |
} | |
}; | |
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, verifier); | |
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory>create() | |
.register("http", PlainConnectionSocketFactory.getSocketFactory()) | |
.register("https", sslConnectionSocketFactory) | |
.build()); | |
connectionManager.setMaxTotal(500); | |
connectionManager.setDefaultMaxPerRoute(200); | |
return HttpClients.custom() | |
.setConnectionManager(connectionManager) | |
.setSSLSocketFactory(sslConnectionSocketFactory) | |
.setDefaultCookieStore(cookieStore) | |
.build(); | |
} catch (Throwable e) { | |
e.printStackTrace(); | |
} | |
return HttpClients.createDefault(); | |
} | |
/** | |
* 实例化一个{@link CloseableHttpClient} | |
* | |
* @return | |
*/ | |
private static CloseableHttpClient buildHttpClient() { | |
final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); | |
connectionManager.setMaxTotal(500); | |
connectionManager.setDefaultMaxPerRoute(200); | |
try { | |
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { | |
public boolean isTrusted(X509Certificate[] chain, | |
String authType) throws CertificateException { | |
return true; | |
} | |
}).build(); | |
return HttpClients.custom() | |
.setConnectionManager(connectionManager) | |
.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) | |
.setDefaultCookieStore(cookieStore) | |
.build(); | |
} catch (Throwable e) { | |
e.printStackTrace(); | |
} | |
return HttpClients.createDefault(); | |
} | |
public static CookieStore getCookieStore() { | |
return cookieStore; | |
} | |
private static String executeForString(HttpUriRequest request) { | |
if (request != null) { | |
try (CloseableHttpResponse response = CLIENT.execute(request)) { | |
HttpEntity entity = response.getEntity(); | |
if (entity != null) { | |
return EntityUtils.toString(entity, Const.DEFAULT_CHATSET); | |
} | |
} catch (Throwable e) { | |
e.printStackTrace(); | |
} | |
} | |
return null; | |
} | |
private static byte[] executeForBytes(HttpUriRequest request) { | |
if (request != null) { | |
try (CloseableHttpResponse response = CLIENT.execute(request)) { | |
HttpEntity entity = response.getEntity(); | |
if (entity != null) { | |
return EntityUtils.toByteArray(entity); | |
} | |
} catch (Throwable e) { | |
e.printStackTrace(); | |
} | |
} | |
return null; | |
} | |
public static String getForString(URI uri) { | |
if (uri != null) { | |
return executeForString(new HttpGet(uri)); | |
} | |
return null; | |
} | |
public static String getForString(String uri, Map<String, Object> params) throws URISyntaxException { | |
final URIBuilder uriBuilder = new URIBuilder(uri); | |
uriBuilder.setCharset(Charset.forName(Const.DEFAULT_CHATSET)); | |
if (params!=null){ | |
for (Map.Entry<String, Object> entry : params.entrySet()) { | |
uriBuilder.setParameter(entry.getKey(), entry.getValue().toString()); | |
} | |
} | |
return getForString(uriBuilder.build()); | |
} | |
public static byte[] getToBytes(URI uri) { | |
if (uri != null) { | |
return executeForBytes(new HttpGet(uri)); | |
} | |
return null; | |
} | |
public static boolean getToFile(final URI uri, final File file) { | |
if (uri != null && file != null) { | |
final File path = file.getParentFile(); | |
if (!path.exists()) { | |
path.mkdirs(); | |
} | |
try (CloseableHttpResponse response = CLIENT.execute(new HttpGet(uri))) { | |
final HttpEntity entity = response.getEntity(); | |
if (entity != null) { | |
try (FileOutputStream os = new FileOutputStream(file)) { | |
entity.writeTo(os); | |
return true; | |
} | |
} | |
} catch (Throwable e) { | |
e.printStackTrace(); | |
} | |
} | |
return false; | |
} | |
public static String postForString(String uri, Map<String, Object> params) throws UnsupportedEncodingException { | |
if (uri==null){ | |
return null; | |
} | |
final HttpPost httpPost = new HttpPost(uri); | |
if (params != null) { | |
final List<NameValuePair> parameters = new ArrayList<>(); | |
for (Map.Entry<String, Object> entry : params.entrySet()) { | |
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString())); | |
} | |
httpPost.setEntity(new UrlEncodedFormEntity(parameters, Const.DEFAULT_CHATSET)); | |
} | |
return executeForString(httpPost); | |
} | |
public static String postForFile(URI uri, Map<String, Object> map) { | |
if (uri != null) { | |
final HttpPost post = new HttpPost(uri); | |
MultipartEntityBuilder builder = MultipartEntityBuilder.create(); | |
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); | |
ContentType contentType = ContentType.create("multipart/form-data", Const.DEFAULT_CHATSET); | |
builder.setContentType(contentType); | |
if (map != null && map.size() > 0) { | |
for (Map.Entry<String, Object> entry : map.entrySet()) { | |
String key = entry.getKey(); | |
Object value = entry.getValue(); | |
if (value != null && value instanceof File) { | |
builder.addPart(key, new FileBody((File) value, ContentType.DEFAULT_BINARY)); | |
} else { | |
builder.addPart(key, new StringBody(value == null ? "" : value.toString(), contentType)); | |
} | |
} | |
} | |
HttpEntity entity = builder.build(); | |
post.setEntity(entity); | |
return executeForString(post); | |
} | |
return null; | |
} | |
/** | |
* 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址; | |
* | |
* @param request | |
* @return | |
* @throws IOException | |
*/ | |
public final static String getIpAddress(HttpServletRequest request) throws IOException { | |
// 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 | |
String ip = request.getHeader("X-Forwarded-For"); | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getHeader("Proxy-Client-IP"); | |
} | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getHeader("WL-Proxy-Client-IP"); | |
} | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getHeader("HTTP_CLIENT_IP"); | |
} | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getHeader("HTTP_X_FORWARDED_FOR"); | |
} | |
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { | |
ip = request.getRemoteAddr(); | |
} | |
} else if (ip.length() > 15) { | |
String[] ips = ip.split(","); | |
for (int index = 0; index < ips.length; index++) { | |
String strIp = (String) ips[index]; | |
if (!("unknown".equalsIgnoreCase(strIp))) { | |
ip = strIp; | |
break; | |
} | |
} | |
} | |
return ip; | |
} | |
public static void main(String[] args) throws IOException, URISyntaxException { | |
System.out.printf(getForString(new URI("https://api.ihansen.org"))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment