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

加方法

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