Commit e99f0ab9 authored by Quxl's avatar Quxl
parents 88ea43ff 7fcefa52
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.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
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;
}
/**
* 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应
*
* @param url
* 请求地址 form表单url地址
* @param filePath
* 文件在服务器保存路径
* @return String url的响应信息返回值
* @throws IOException
*/
public static String doPostByFile(String url, String filePath) throws IOException {
String result = null;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
throw new IOException("文件不存在");
}
/**
* 第一部分
*/
URL urlObj = new URL(url);
// 连接
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
/**
* 设置关键值
*/
con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post方式不能使用缓存
// 设置请求头信息
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
// 设置边界
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
// 请求正文信息
// 第一部分:
StringBuilder sb = new StringBuilder();
sb.append("--"); // 必须多两道线
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] head = sb.toString().getBytes("utf-8");
// 获得输出流
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