Commit 6b2beab5 authored by 张永's avatar 张永

加方法

parent 9a815612
package com.egolm.common; package com.egolm.common;
import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
......
package com.egolm.common; package com.egolm.common;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.Proxy; import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.KeyStore; import java.security.KeyStore;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.HashMap;
import java.util.Map; import java.util.List;
import java.util.regex.Matcher; import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity; import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.ssl.SSLContexts; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import com.egolm.common.exception.HttpRequestException;
import com.egolm.common.exception.HttpRequestException;
/**
* /**
* @author 曲欣亮 *
* @since 2015-04-01 * @author 曲欣亮
* * @since 2015-04-01
*/ *
public class HttpsUtil { */
private static RequestConfig requestConfig; public class HttpsUtil {
static { private static RequestConfig requestConfig;
RequestConfig.Builder configBuilder = RequestConfig.custom(); static {
// 设置连接超时 RequestConfig.Builder configBuilder = RequestConfig.custom();
configBuilder.setConnectTimeout(10*1000); // 设置连接超时
// 设置读取超时 configBuilder.setConnectTimeout(10*1000);
configBuilder.setSocketTimeout(10*10000); // 设置读取超时
requestConfig = configBuilder.build(); configBuilder.setSocketTimeout(10*10000);
} requestConfig = configBuilder.build();
}
/**
* 发送无参数的GET请求 /**
*/ * 发送无参数的GET请求
public static String doGet(String url) { */
return doGet(url,null); public static String doGet(String url) {
} return doGet(url,null);
}
/**
* 发送有参数的GET请求,参数为MAP key-value格式 /**
*/ * 发送有参数的GET请求,参数为MAP key-value格式
public static String doGet(String url, Map<String, String> params) { */
List<String> paramList=new ArrayList<String>(); public static String doGet(String url, Map<String, String> params) {
if(params!=null){ List<String> paramList=new ArrayList<String>();
for (String key : params.keySet()) { if(params!=null){
paramList.add(key+"="+params.get(key)); for (String key : params.keySet()) {
} paramList.add(key+"="+params.get(key));
if(paramList.size()>0){ }
if(url.indexOf("?")==-1){ if(paramList.size()>0){
url=url+"?"+StringUtil.join("&",paramList); if(url.indexOf("?")==-1){
}else{ url=url+"?"+StringUtil.join("&",paramList);
url=url+"&"+StringUtil.join("&",paramList); }else{
} url=url+"&"+StringUtil.join("&",paramList);
} }
} }
System.out.println("doGet--"+url); }
CloseableHttpClient httpclient = HttpClients.createDefault(); System.out.println("doGet--"+url);
HttpGet httpGet = new HttpGet(url.replaceAll(" ", "%20")); CloseableHttpClient httpclient = HttpClients.createDefault();
httpGet.setConfig(requestConfig); HttpGet httpGet = new HttpGet(url.replaceAll(" ", "%20"));
CloseableHttpResponse response = null; httpGet.setConfig(requestConfig);
HttpEntity entity = null; CloseableHttpResponse response = null;
try { HttpEntity entity = null;
response = httpclient.execute(httpGet); try {
entity = response.getEntity(); response = httpclient.execute(httpGet);
String result = EntityUtils.toString(entity, "UTF-8"); entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
} catch (Exception e) { return result;
throw new HttpRequestException(e); } catch (Exception e) {
} finally { throw new HttpRequestException(e);
try { } finally {
if(entity!=null){ try {
EntityUtils.consume(entity); if(entity!=null){
} EntityUtils.consume(entity);
} catch (IOException e) { }
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
try { }
if(response!=null){ try {
response.close(); if(response!=null){
} response.close();
} catch (IOException e) { }
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
}
try {
httpclient.close(); try {
} catch (IOException e) { httpclient.close();
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
} }
} }
public static String get(String requestUrl, Map<String, Object> parameters, Map<String, String> header, Proxy proxy, SSLSocketFactory sslSocketFactory) throws HttpRequestException { }
HttpsURLConnection connection = null; public static String get(String requestUrl, Map<String, Object> parameters, Map<String, String> header, Proxy proxy, SSLSocketFactory sslSocketFactory) throws HttpRequestException {
try { HttpsURLConnection connection = null;
String requestBody = HttpUtil.toQueryString(parameters, "utf-8"); try {
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody; String requestBody = HttpUtil.toQueryString(parameters, "utf-8");
URL GET_URL = new URL(requestUrl); requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody;
connection = (HttpsURLConnection) (proxy == null ? GET_URL.openConnection() : GET_URL.openConnection(proxy)); URL GET_URL = new URL(requestUrl);
connection.setSSLSocketFactory(sslSocketFactory); connection = (HttpsURLConnection) (proxy == null ? GET_URL.openConnection() : GET_URL.openConnection(proxy));
connection.setRequestMethod("GET"); connection.setSSLSocketFactory(sslSocketFactory);
connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Accept-Charset", "utf-8");
if (header != null) { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
for (String key : header.keySet()) { if (header != null) {
connection.setRequestProperty(key, header.get(key)); for (String key : header.keySet()) {
} connection.setRequestProperty(key, header.get(key));
} }
connection.connect(); }
return HttpUtil.responseBody(connection); connection.connect();
} catch (Exception e) { return HttpUtil.responseBody(connection);
throw new HttpRequestException("HTTP(GET)请求异常", e); } catch (Exception e) {
} finally { throw new HttpRequestException("HTTP(GET)请求异常", e);
connection.disconnect(); } finally {
} connection.disconnect();
} }
}
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
return HttpsUtil.post(requestUrl, HttpUtil.toQueryString(parameters), headers, sslSocketFactory, proxy); public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
} return HttpsUtil.post(requestUrl, HttpUtil.toQueryString(parameters), headers, sslSocketFactory, proxy);
}
public static String post(String requestUrl, String text, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
HttpsURLConnection connection = null; public static String post(String requestUrl, String text, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
try { HttpsURLConnection connection = null;
byte[] bytes = text == null ? new byte[0] : text.getBytes(); try {
URL POST_URL = new URL(requestUrl); byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection = (HttpsURLConnection) (proxy == null ? POST_URL.openConnection() : POST_URL.openConnection(proxy)); URL POST_URL = new URL(requestUrl);
connection.setSSLSocketFactory(sslSocketFactory); connection = (HttpsURLConnection) (proxy == null ? POST_URL.openConnection() : POST_URL.openConnection(proxy));
connection.setDoOutput(true); connection.setSSLSocketFactory(sslSocketFactory);
connection.setDoInput(true); connection.setDoOutput(true);
connection.setRequestMethod("POST"); connection.setDoInput(true);
connection.setUseCaches(false); connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true); connection.setUseCaches(false);
connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (headers != null) { connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
for (String key : headers.keySet()) { if (headers != null) {
connection.setRequestProperty(key, headers.get(key)); for (String key : headers.keySet()) {
} connection.setRequestProperty(key, headers.get(key));
} }
OutputStream out = connection.getOutputStream(); }
out.write(bytes); OutputStream out = connection.getOutputStream();
out.close(); out.write(bytes);
return HttpUtil.responseBody(connection); out.close();
} catch (Exception e) { return HttpUtil.responseBody(connection);
throw new HttpRequestException("HTTP(POST)请求异常", e); } catch (Exception e) {
} finally { throw new HttpRequestException("HTTP(POST)请求异常", e);
connection.disconnect(); } finally {
} connection.disconnect();
} }
}
/**
* /**
* <p> *
* Title: 发送XML的post请求 * <p>
* </p> * Title: 发送XML的post请求
* <p> * </p>
* Description: * <p>
* </p> * Description:
* * </p>
* @param url *
* @param xml * @param url
* @return * @param xml
*/ * @return
public static String doPostForXml(String url, String xml) { */
CloseableHttpClient httpClient = HttpClients.createDefault(); public static String doPostForXml(String url, String xml) {
HttpPost httpPost = new HttpPost(url); CloseableHttpClient httpClient = HttpClients.createDefault();
httpPost.setConfig(requestConfig); HttpPost httpPost = new HttpPost(url);
CloseableHttpResponse response = null; httpPost.setConfig(requestConfig);
HttpEntity entity = null; CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8"))); try {
httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8")));
response = httpClient.execute(httpPost);
entity = response.getEntity(); response = httpClient.execute(httpPost);
String result = EntityUtils.toString(entity, "UTF-8"); entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
} catch (Exception e) { return result;
throw new HttpRequestException(e); } catch (Exception e) {
} finally { throw new HttpRequestException(e);
try { } finally {
if (entity != null) { try {
EntityUtils.consume(entity); if (entity != null) {
} EntityUtils.consume(entity);
} catch (IOException e) { }
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
}
try {
if (response != null) { try {
response.close(); if (response != null) {
} response.close();
} catch (IOException e) { }
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
}
try {
httpClient.close(); try {
} catch (IOException e) { httpClient.close();
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
} }
} }
/** }
* 调用证书进行退款 WX提供 /**
* * 发送有参数的POST请求,参数为json格式
* @param servicePartner */
* 商户号 public static String doPostForJson(String url, String json) {
* @param sslPath Map<String, String> map = new HashMap<String, String>();
* 证书地址 "D:/10016225.p12" String result = HttpUtil.post(url, json, map,null);
* @throws Exception return result;
*/ }
public static String doPostBySSL(String servicePartner, String sslPath, String xml, String requestUrl)
throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12"); /**
FileInputStream instream = new FileInputStream(new File(sslPath)); * 调用证书进行退款 WX提供
keyStore.load(instream, servicePartner.toCharArray()); *
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, servicePartner.toCharArray()).build(); * @param servicePartner
byte[] bytes = xml == null ? new byte[0] : xml.getBytes(); * 商户号
URL POST_URL = new URL(requestUrl); * @param sslPath
HttpsURLConnection connection = (HttpsURLConnection) POST_URL.openConnection(); * 证书地址 "D:/10016225.p12"
connection.setSSLSocketFactory(sslcontext.getSocketFactory()); * @throws Exception
connection.setDoOutput(true); */
connection.setDoInput(true); public static String doPostBySSL(String servicePartner, String sslPath, String xml, String requestUrl)
connection.setRequestMethod("POST"); throws Exception {
connection.setUseCaches(false); KeyStore keyStore = KeyStore.getInstance("PKCS12");
connection.setInstanceFollowRedirects(true); FileInputStream instream = new FileInputStream(new File(sslPath));
connection.setRequestProperty("Accept-Charset", "utf-8"); keyStore.load(instream, servicePartner.toCharArray());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, servicePartner.toCharArray()).build();
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); byte[] bytes = xml == null ? new byte[0] : xml.getBytes();
OutputStream out = connection.getOutputStream(); URL POST_URL = new URL(requestUrl);
out.write(bytes); HttpsURLConnection connection = (HttpsURLConnection) POST_URL.openConnection();
out.close(); connection.setSSLSocketFactory(sslcontext.getSocketFactory());
return responseBody(connection); connection.setDoOutput(true);
} connection.setDoInput(true);
connection.setRequestMethod("POST");
public static String responseBody(HttpURLConnection connection) throws Exception { connection.setUseCaches(false);
byte[] bytes; connection.setInstanceFollowRedirects(true);
try { connection.setRequestProperty("Accept-Charset", "utf-8");
bytes = FileUtil.streamToBytes(connection.getInputStream()); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
} catch (IOException e) { connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
bytes = FileUtil.streamToBytes(connection.getErrorStream()); OutputStream out = connection.getOutputStream();
} out.write(bytes);
String strHtml = null; out.close();
Map<String, List<String>> responseHeaders = connection.getHeaderFields(); return responseBody(connection);
List<String> contentTypes = responseHeaders.get("Content-Type"); }
String responseCharsetName = null;
String contentType = (contentTypes != null && contentTypes.size() > 0) ? contentTypes.get(0) : ""; public static String responseBody(HttpURLConnection connection) throws Exception {
String[] typeArray = contentType.split(";"); byte[] bytes;
for (String type : typeArray) { try {
if (type.startsWith("charset=")) { bytes = FileUtil.streamToBytes(connection.getInputStream());
responseCharsetName = type.split("=", 2)[1]; } catch (IOException e) {
} else if (type.startsWith("encoding=")) { bytes = FileUtil.streamToBytes(connection.getErrorStream());
responseCharsetName = type.split("=", 2)[1]; }
} String strHtml = null;
} Map<String, List<String>> responseHeaders = connection.getHeaderFields();
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { List<String> contentTypes = responseHeaders.get("Content-Type");
strHtml = new String(bytes, "utf-8"); String responseCharsetName = null;
String regex = "charset=([^\"'>]+)"; String contentType = (contentTypes != null && contentTypes.size() > 0) ? contentTypes.get(0) : "";
Pattern pattern = Pattern.compile(regex); String[] typeArray = contentType.split(";");
Matcher matcher = pattern.matcher(strHtml); for (String type : typeArray) {
while (matcher.find()) { if (type.startsWith("charset=")) {
String metaCharsetName = matcher.group(1); responseCharsetName = type.split("=", 2)[1];
if (metaCharsetName != null && metaCharsetName.trim().length() > 0) { } else if (type.startsWith("encoding=")) {
responseCharsetName = metaCharsetName; responseCharsetName = type.split("=", 2)[1];
} }
} }
} if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { strHtml = new String(bytes, "utf-8");
return strHtml; String regex = "charset=([^\"'>]+)";
} else { Pattern pattern = Pattern.compile(regex);
return new String(bytes, responseCharsetName); Matcher matcher = pattern.matcher(strHtml);
} while (matcher.find()) {
} String metaCharsetName = matcher.group(1);
if (metaCharsetName != null && metaCharsetName.trim().length() > 0) {
} responseCharsetName = metaCharsetName;
}
}
}
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
return strHtml;
} else {
return new String(bytes, responseCharsetName);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment