Commit e99f0ab9 authored by Quxl's avatar Quxl
parents 88ea43ff 7fcefa52
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.BufferedReader;
import java.io.FileInputStream; import java.io.DataInputStream;
import java.io.IOException; import java.io.DataOutputStream;
import java.io.OutputStream; import java.io.File;
import java.net.HttpURLConnection; import java.io.FileInputStream;
import java.net.Proxy; import java.io.IOException;
import java.net.URL; import java.io.InputStreamReader;
import java.nio.charset.Charset; import java.io.OutputStream;
import java.security.KeyStore; import java.net.HttpURLConnection;
import java.util.ArrayList; import java.net.Proxy;
import java.util.List; import java.net.URL;
import java.util.Map; import java.nio.charset.Charset;
import java.util.regex.Matcher; import java.security.KeyStore;
import java.util.regex.Pattern; import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection; import java.util.List;
import javax.net.ssl.SSLContext; import java.util.Map;
import javax.net.ssl.SSLSocketFactory; import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig; import javax.net.ssl.HttpsURLConnection;
import org.apache.http.client.methods.CloseableHttpResponse; import javax.net.ssl.SSLContext;
import org.apache.http.client.methods.HttpGet; import javax.net.ssl.SSLSocketFactory;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.HttpEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.ssl.SSLContexts; import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import com.egolm.common.exception.HttpRequestException; 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;
*
* @author 曲欣亮 import com.egolm.common.exception.HttpRequestException;
* @since 2015-04-01
*
*/ /**
public class HttpsUtil { *
private static RequestConfig requestConfig; * @author 曲欣亮
static { * @since 2015-04-01
RequestConfig.Builder configBuilder = RequestConfig.custom(); *
// 设置连接超时 */
configBuilder.setConnectTimeout(10*1000); public class HttpsUtil {
// 设置读取超时 private static RequestConfig requestConfig;
configBuilder.setSocketTimeout(10*10000); static {
requestConfig = configBuilder.build(); RequestConfig.Builder configBuilder = RequestConfig.custom();
} // 设置连接超时
configBuilder.setConnectTimeout(10*1000);
/** // 设置读取超时
* 发送无参数的GET请求 configBuilder.setSocketTimeout(10*10000);
*/ requestConfig = configBuilder.build();
public static String doGet(String url) { }
return doGet(url,null);
} /**
* 发送无参数的GET请求
/** */
* 发送有参数的GET请求,参数为MAP key-value格式 public static String doGet(String url) {
*/ return doGet(url,null);
public static String doGet(String url, Map<String, String> params) { }
List<String> paramList=new ArrayList<String>();
if(params!=null){ /**
for (String key : params.keySet()) { * 发送有参数的GET请求,参数为MAP key-value格式
paramList.add(key+"="+params.get(key)); */
} public static String doGet(String url, Map<String, String> params) {
if(paramList.size()>0){ List<String> paramList=new ArrayList<String>();
if(url.indexOf("?")==-1){ if(params!=null){
url=url+"?"+StringUtil.join("&",paramList); for (String key : params.keySet()) {
}else{ paramList.add(key+"="+params.get(key));
url=url+"&"+StringUtil.join("&",paramList); }
} if(paramList.size()>0){
} if(url.indexOf("?")==-1){
} url=url+"?"+StringUtil.join("&",paramList);
System.out.println("doGet--"+url); }else{
CloseableHttpClient httpclient = HttpClients.createDefault(); url=url+"&"+StringUtil.join("&",paramList);
HttpGet httpGet = new HttpGet(url.replaceAll(" ", "%20")); }
httpGet.setConfig(requestConfig); }
CloseableHttpResponse response = null; }
HttpEntity entity = null; System.out.println("doGet--"+url);
try { CloseableHttpClient httpclient = HttpClients.createDefault();
response = httpclient.execute(httpGet); HttpGet httpGet = new HttpGet(url.replaceAll(" ", "%20"));
entity = response.getEntity(); httpGet.setConfig(requestConfig);
String result = EntityUtils.toString(entity, "UTF-8"); CloseableHttpResponse response = null;
HttpEntity entity = null;
return result; try {
} catch (Exception e) { response = httpclient.execute(httpGet);
throw new HttpRequestException(e); entity = response.getEntity();
} finally { String result = EntityUtils.toString(entity, "UTF-8");
try {
if(entity!=null){ return result;
EntityUtils.consume(entity); } catch (Exception e) {
} throw new HttpRequestException(e);
} catch (IOException e) { } finally {
e.printStackTrace(); try {
} if(entity!=null){
try { EntityUtils.consume(entity);
if(response!=null){ }
response.close(); } catch (IOException e) {
} e.printStackTrace();
} catch (IOException e) { }
e.printStackTrace(); try {
} if(response!=null){
response.close();
try { }
httpclient.close(); } catch (IOException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); }
}
} try {
} httpclient.close();
public static String get(String requestUrl, Map<String, Object> parameters, Map<String, String> header, Proxy proxy, SSLSocketFactory sslSocketFactory) throws HttpRequestException { } catch (IOException e) {
HttpsURLConnection connection = null; e.printStackTrace();
try { }
String requestBody = HttpUtil.toQueryString(parameters, "utf-8"); }
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody; }
URL GET_URL = new URL(requestUrl); public static String get(String requestUrl, Map<String, Object> parameters, Map<String, String> header, Proxy proxy, SSLSocketFactory sslSocketFactory) throws HttpRequestException {
connection = (HttpsURLConnection) (proxy == null ? GET_URL.openConnection() : GET_URL.openConnection(proxy)); HttpsURLConnection connection = null;
connection.setSSLSocketFactory(sslSocketFactory); try {
connection.setRequestMethod("GET"); String requestBody = HttpUtil.toQueryString(parameters, "utf-8");
connection.setRequestProperty("Accept-Charset", "utf-8"); requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody;
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); URL GET_URL = new URL(requestUrl);
if (header != null) { connection = (HttpsURLConnection) (proxy == null ? GET_URL.openConnection() : GET_URL.openConnection(proxy));
for (String key : header.keySet()) { connection.setSSLSocketFactory(sslSocketFactory);
connection.setRequestProperty(key, header.get(key)); connection.setRequestMethod("GET");
} connection.setRequestProperty("Accept-Charset", "utf-8");
} connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect(); if (header != null) {
return HttpUtil.responseBody(connection); for (String key : header.keySet()) {
} catch (Exception e) { connection.setRequestProperty(key, header.get(key));
throw new HttpRequestException("HTTP(GET)请求异常", e); }
} finally { }
connection.disconnect(); connection.connect();
} return HttpUtil.responseBody(connection);
} } catch (Exception e) {
throw new HttpRequestException("HTTP(GET)请求异常", e);
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException { } finally {
return HttpsUtil.post(requestUrl, HttpUtil.toQueryString(parameters), headers, sslSocketFactory, proxy); connection.disconnect();
} }
}
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, Map<String, Object> parameters, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
try { return HttpsUtil.post(requestUrl, HttpUtil.toQueryString(parameters), headers, sslSocketFactory, proxy);
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)); public static String post(String requestUrl, String text, Map<String, String> headers, SSLSocketFactory sslSocketFactory, Proxy proxy) throws HttpRequestException {
connection.setSSLSocketFactory(sslSocketFactory); HttpsURLConnection connection = null;
connection.setDoOutput(true); try {
connection.setDoInput(true); byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection.setRequestMethod("POST"); URL POST_URL = new URL(requestUrl);
connection.setUseCaches(false); connection = (HttpsURLConnection) (proxy == null ? POST_URL.openConnection() : POST_URL.openConnection(proxy));
connection.setInstanceFollowRedirects(true); connection.setSSLSocketFactory(sslSocketFactory);
connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoInput(true);
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); connection.setRequestMethod("POST");
if (headers != null) { connection.setUseCaches(false);
for (String key : headers.keySet()) { connection.setInstanceFollowRedirects(true);
connection.setRequestProperty(key, headers.get(key)); 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(); if (headers != null) {
out.write(bytes); for (String key : headers.keySet()) {
out.close(); connection.setRequestProperty(key, headers.get(key));
return HttpUtil.responseBody(connection); }
} catch (Exception e) { }
throw new HttpRequestException("HTTP(POST)请求异常", e); OutputStream out = connection.getOutputStream();
} finally { out.write(bytes);
connection.disconnect(); 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> * <p>
* * Title: 发送XML的post请求
* @param url * </p>
* @param xml * <p>
* @return * Description:
*/ * </p>
public static String doPostForXml(String url, String xml) { *
CloseableHttpClient httpClient = HttpClients.createDefault(); * @param url
HttpPost httpPost = new HttpPost(url); * @param xml
httpPost.setConfig(requestConfig); * @return
CloseableHttpResponse response = null; */
HttpEntity entity = null; public static String doPostForXml(String url, String xml) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try { HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8"))); httpPost.setConfig(requestConfig);
CloseableHttpResponse response = null;
response = httpClient.execute(httpPost); HttpEntity entity = null;
entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8"); try {
httpPost.setEntity(new StringEntity(xml, Charset.forName("UTF-8")));
return result;
} catch (Exception e) { response = httpClient.execute(httpPost);
throw new HttpRequestException(e); entity = response.getEntity();
} finally { String result = EntityUtils.toString(entity, "UTF-8");
try {
if (entity != null) { return result;
EntityUtils.consume(entity); } catch (Exception e) {
} throw new HttpRequestException(e);
} catch (IOException e) { } finally {
e.printStackTrace(); try {
} if (entity != null) {
EntityUtils.consume(entity);
try { }
if (response != null) { } catch (IOException e) {
response.close(); e.printStackTrace();
} }
} catch (IOException e) {
e.printStackTrace(); try {
} if (response != null) {
response.close();
try { }
httpClient.close(); } catch (IOException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); }
}
} try {
} httpClient.close();
/** } catch (IOException e) {
* 调用证书进行退款 WX提供 e.printStackTrace();
* }
* @param servicePartner }
* 商户号 }
* @param sslPath /**
* 证书地址 "D:/10016225.p12" * 发送有参数的POST请求,参数为json格式
* @throws Exception */
*/ public static String doPostForJson(String url, String json) {
public static String doPostBySSL(String servicePartner, String sslPath, String xml, String requestUrl) Map<String, String> map = new HashMap<String, String>();
throws Exception { String result = HttpUtil.post(url, json, map,null);
KeyStore keyStore = KeyStore.getInstance("PKCS12"); return result;
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); * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
HttpsURLConnection connection = (HttpsURLConnection) POST_URL.openConnection(); *
connection.setSSLSocketFactory(sslcontext.getSocketFactory()); * @param url
connection.setDoOutput(true); * 请求地址 form表单url地址
connection.setDoInput(true); * @param filePath
connection.setRequestMethod("POST"); * 文件在服务器保存路径
connection.setUseCaches(false); * @return String url的响应信息返回值
connection.setInstanceFollowRedirects(true); * @throws IOException
connection.setRequestProperty("Accept-Charset", "utf-8"); */
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); public static String doPostByFile(String url, String filePath) throws IOException {
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
OutputStream out = connection.getOutputStream(); String result = null;
out.write(bytes);
out.close(); File file = new File(filePath);
return responseBody(connection); if (!file.exists() || !file.isFile()) {
} throw new IOException("文件不存在");
}
public static String responseBody(HttpURLConnection connection) throws Exception {
byte[] bytes; /**
try { * 第一部分
bytes = FileUtil.streamToBytes(connection.getInputStream()); */
} catch (IOException e) { URL urlObj = new URL(url);
bytes = FileUtil.streamToBytes(connection.getErrorStream()); // 连接
} HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
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) : ""; con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
String[] typeArray = contentType.split(";"); con.setDoInput(true);
for (String type : typeArray) { con.setDoOutput(true);
if (type.startsWith("charset=")) { con.setUseCaches(false); // post方式不能使用缓存
responseCharsetName = type.split("=", 2)[1];
} else if (type.startsWith("encoding=")) { // 设置请求头信息
responseCharsetName = type.split("=", 2)[1]; con.setRequestProperty("Connection", "Keep-Alive");
} con.setRequestProperty("Charset", "UTF-8");
}
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { // 设置边界
strHtml = new String(bytes, "utf-8"); String BOUNDARY = "----------" + System.currentTimeMillis();
String regex = "charset=([^\"'>]+)"; con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
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) { StringBuilder sb = new StringBuilder();
responseCharsetName = metaCharsetName; sb.append("--"); // 必须多两道线
} sb.append(BOUNDARY);
} sb.append("\r\n");
} sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { sb.append("Content-Type:application/octet-stream\r\n\r\n");
return strHtml;
} else { byte[] head = sb.toString().getBytes("utf-8");
return new String(bytes, responseCharsetName);
} // 获得输出流
} OutputStream out = new DataOutputStream(con.getOutputStream());
// 输出表头
} out.write(head);
// 文件正文部分
// 把文件已流文件的方式 推入到url中
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
// 结尾部分
byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
out.write(foot);
out.flush();
out.close();
StringBuffer buffer = new StringBuffer();
BufferedReader reader = null;
try {
// 定义BufferedReader输入流来读取URL的响应
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
// System.out.println(line);
buffer.append(line);
}
if (result == null) {
result = buffer.toString();
}
} catch (IOException e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
throw new IOException("数据读取异常");
} finally {
if (reader != null) {
reader.close();
}
}
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