Commit 260f1b2f authored by 张永's avatar 张永

1

parent a6b9a65c
package com.egolm.common; package com.egolm.common;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
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.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
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.net.URLEncoder; import java.net.URLEncoder;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import com.egolm.common.exception.HttpRequestException; import com.egolm.common.exception.HttpRequestException;
import com.egolm.common.exception.HttpResponseException; import com.egolm.common.exception.HttpResponseException;
import com.egolm.common.exception.HttpUrlEncodingException; import com.egolm.common.exception.HttpUrlEncodingException;
/** /**
* *
* @author 曲欣亮 * @author 曲欣亮
* @since 2015-04-01 * @since 2015-04-01
* *
*/ */
public class HttpUtil { public class HttpUtil {
static { static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
} }
private static final String charset = "utf-8"; private static final String charset = "utf-8";
private static SSLContext sslContextDefault = null; private static SSLContext sslContextDefault = null;
private static class TrustAnyTrustManager implements X509TrustManager { private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} }
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} }
public X509Certificate[] getAcceptedIssuers() { public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {}; return new X509Certificate[] {};
} }
} }
private static SSLContext getDefaultSSLContext() { private static SSLContext getDefaultSSLContext() {
if (sslContextDefault == null) { if (sslContextDefault == null) {
try { try {
sslContextDefault = SSLContext.getInstance("SSL"); sslContextDefault = SSLContext.getInstance("SSL");
sslContextDefault.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom()); sslContextDefault.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return sslContextDefault; return sslContextDefault;
} }
private static HttpURLConnection createConnection(String requestUrl, Proxy proxy) throws IOException{ private static HttpURLConnection createConnection(String requestUrl, Proxy proxy) throws IOException{
URL HTTP_URL = new URL(requestUrl); URL HTTP_URL = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) (proxy == null ? HTTP_URL.openConnection() : HTTP_URL.openConnection(proxy)); HttpURLConnection connection = (HttpURLConnection) (proxy == null ? HTTP_URL.openConnection() : HTTP_URL.openConnection(proxy));
if (requestUrl.startsWith("https")) { if (requestUrl.startsWith("https")) {
((HttpsURLConnection) connection).setSSLSocketFactory(getDefaultSSLContext().getSocketFactory()); ((HttpsURLConnection) connection).setSSLSocketFactory(getDefaultSSLContext().getSocketFactory());
} }
return connection; return connection;
} }
public static String get(String requestUrl) throws HttpRequestException { public static String get(String requestUrl) throws HttpRequestException {
return HttpUtil.get(requestUrl, null, null, null); return HttpUtil.get(requestUrl, null, null, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters) throws HttpRequestException { public static String get(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
return HttpUtil.get(requestUrl, parameters, null, null); return HttpUtil.get(requestUrl, parameters, null, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header) public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header)
throws HttpRequestException { throws HttpRequestException {
return HttpUtil.get(requestUrl, parameters, header, null); return HttpUtil.get(requestUrl, parameters, header, null);
} }
public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header, Proxy proxy) public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
if (requestUrl.startsWith("https")) { if (requestUrl.startsWith("https")) {
} }
String requestBody = HttpUtil.toQueryString(parameters, charset); String requestBody = HttpUtil.toQueryString(parameters, charset);
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?")
+ requestBody; + requestBody;
System.out.println(requestUrl); System.out.println(requestUrl);
connection = createConnection(requestUrl, proxy); connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET"); connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (header != null) { if (header != null) {
for (String key : header.keySet()) { for (String key : header.keySet()) {
connection.setRequestProperty(key, header.get(key)); connection.setRequestProperty(key, header.get(key));
} }
} }
connection.connect(); connection.connect();
return responseBody(connection); return responseBody(connection);
} catch (Exception e) { } catch (Exception e) {
throw new HttpRequestException("HTTP(GET)请求异常", e); throw new HttpRequestException("HTTP(GET)请求异常", e);
} finally { } finally {
connection.disconnect(); connection.disconnect();
} }
} }
public static String post(String requestUrl) throws HttpRequestException { public static String post(String requestUrl) throws HttpRequestException {
return HttpUtil.post(requestUrl, null); return HttpUtil.post(requestUrl, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters) throws HttpRequestException { public static String post(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
return HttpUtil.post(requestUrl, parameters, null); return HttpUtil.post(requestUrl, parameters, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers) public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers)
throws HttpRequestException { throws HttpRequestException {
return HttpUtil.post(requestUrl, parameters, headers, null); return HttpUtil.post(requestUrl, parameters, headers, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers, Proxy proxy) public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
return post(requestUrl, HttpUtil.toQueryString(parameters, charset), headers, proxy); return post(requestUrl, HttpUtil.toQueryString(parameters, charset), headers, proxy);
} }
public static String post(String requestUrl, String text, Map<String, String> headers, Proxy proxy) public static String post(String requestUrl, String text, Map<String, String> headers, Proxy proxy)
throws HttpRequestException { throws HttpRequestException {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
byte[] bytes = text == null ? new byte[0] : text.getBytes(); byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection = createConnection(requestUrl, proxy); connection = createConnection(requestUrl, proxy);
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setDoInput(true); connection.setDoInput(true);
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setUseCaches(false); connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true); connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(bytes.length)); connection.setRequestProperty("Content-Length", String.valueOf(bytes.length));
if (headers != null) { if (headers != null) {
for (String key : headers.keySet()) { for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key)); connection.setRequestProperty(key, headers.get(key));
} }
} }
OutputStream out = connection.getOutputStream(); OutputStream out = connection.getOutputStream();
out.write(bytes); out.write(bytes);
out.close(); out.close();
return responseBody(connection); return responseBody(connection);
} catch (Exception e) { } catch (Exception e) {
throw new HttpRequestException("HTTP(POST)请求异常", e); throw new HttpRequestException("HTTP(POST)请求异常", e);
} finally { } finally {
connection.disconnect(); connection.disconnect();
} }
} }
private static final Pattern pattern = Pattern.compile("charset(\\s+)?=(\\s+)?([0-9a-zA-Z\\-]+)"); private static final Pattern pattern = Pattern.compile("charset(\\s+)?=(\\s+)?([0-9a-zA-Z\\-]+)");
public static String responseBody(HttpURLConnection connection) throws HttpResponseException { public static String responseBody(HttpURLConnection connection) throws HttpResponseException {
try { try {
byte[] bytes; byte[] bytes;
try { try {
bytes = FileUtil.streamToBytes(connection.getInputStream()); bytes = FileUtil.streamToBytes(connection.getInputStream());
} catch (IOException e) { } catch (IOException e) {
bytes = FileUtil.streamToBytes(connection.getErrorStream()); bytes = FileUtil.streamToBytes(connection.getErrorStream());
} }
Map<String, List<String>> responseHeaders = connection.getHeaderFields(); Map<String, List<String>> responseHeaders = connection.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type"); List<String> contentTypes = responseHeaders.get("Content-Type");
String responseCharsetName = null; String responseCharsetName = null;
if (contentTypes != null) { if (contentTypes != null) {
for (String contentType : contentTypes) { for (String contentType : contentTypes) {
Matcher matcher = pattern.matcher(contentType); Matcher matcher = pattern.matcher(contentType);
if (matcher.find()) { if (matcher.find()) {
responseCharsetName = matcher.group(3); responseCharsetName = matcher.group(3);
break; break;
} }
} }
} }
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) { if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
return new String(bytes, charset); return new String(bytes, charset);
} else { } else {
return new String(bytes, responseCharsetName); return new String(bytes, responseCharsetName);
} }
} catch (Exception e) { } catch (Exception e) {
throw new HttpResponseException("获取HTTP请求响应结果异常", e); throw new HttpResponseException("获取HTTP请求响应结果异常", e);
} }
} }
public static Map<String, String[]> toParameters(String queryString) { public static Map<String, String[]> toParameters(String queryString) {
Map<String, List<String>> map = new HashMap<String, List<String>>(); Map<String, List<String>> map = new HashMap<String, List<String>>();
String[] ary = queryString.split("&"); String[] ary = queryString.split("&");
for (String str : ary) { for (String str : ary) {
if (StringUtil.isNotEmpty(str)) { if (StringUtil.isNotEmpty(str)) {
String[] kv = str.split("=", 2); String[] kv = str.split("=", 2);
List<String> list = map.get(kv[0]); List<String> list = map.get(kv[0]);
if (list == null) { if (list == null) {
list = new ArrayList<String>(); list = new ArrayList<String>();
} }
list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null); list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null);
map.put(kv[0], list); map.put(kv[0], list);
} }
} }
Map<String, String[]> params = new HashMap<String, String[]>(); Map<String, String[]> params = new HashMap<String, String[]>();
for (String key : map.keySet()) { for (String key : map.keySet()) {
List<String> list = map.get(key); List<String> list = map.get(key);
params.put(key, list.toArray(new String[list.size()])); params.put(key, list.toArray(new String[list.size()]));
} }
return params; return params;
} }
public static String toQueryString(Map<?, ?> parameters) { public static String toQueryString(Map<?, ?> parameters) {
return toQueryString(parameters, null); return toQueryString(parameters, null);
} }
public static String toQueryString(Map<?, ?> parameters, String encode) throws HttpUrlEncodingException { public static String toQueryString(Map<?, ?> parameters, String encode) throws HttpUrlEncodingException {
try { try {
List<String> params = new ArrayList<String>(); List<String> params = new ArrayList<String>();
if (parameters != null) { if (parameters != null) {
for (Object key : parameters.keySet()) { for (Object key : parameters.keySet()) {
Object val = parameters.get(key); Object val = parameters.get(key);
String sKey = String.valueOf(key); String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val })); : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) { if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) { for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" params.add(sKey + "=" + (sVal == null ? ""
: URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode))); : URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode)));
} }
} else { } else {
params.add("sKey="); params.add("sKey=");
} }
} }
} }
return StringUtil.join("&", params); return StringUtil.join("&", params);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new HttpUrlEncodingException("URL编码异常", e); throw new HttpUrlEncodingException("URL编码异常", e);
} }
} }
public static String formatToQueryString(Map<?, ?> parameters) { public static String formatToQueryString(Map<?, ?> parameters) {
List<String> params = new ArrayList<String>(); List<String> params = new ArrayList<String>();
if (parameters != null) { if (parameters != null) {
for (Object key : parameters.keySet()) { for (Object key : parameters.keySet()) {
Object val = parameters.get(key); Object val = parameters.get(key);
String sKey = String.valueOf(key); String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val })); : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) { if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) { for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : sVal)); if(StringUtil.isNotEmpty(sVal)) {
} System.out.println(sKey+"---"+sVal);
} else { params.add(sKey + "=" +sVal);
params.add(sKey + "="); }
} }
} }
} /*else {
return StringUtil.join("&", params); params.add(sKey + "="); 空值不参与签名
} }*/
}
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, }
Map<String, File> attachments, String contentType) { return StringUtil.join("&", params);
HttpURLConnection connection = null; }
try {
Data data = new Data(); public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers,
String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR"; Map<String, File> attachments, String contentType) {
StringBuffer ParamBuffer = new StringBuffer(); HttpURLConnection connection = null;
if (parameters != null) { try {
for (String key : parameters.keySet()) { Data data = new Data();
ParamBuffer.append("--" + BOUNDARY + "\r\n"); String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n"); StringBuffer ParamBuffer = new StringBuffer();
ParamBuffer.append("\r\n"); if (parameters != null) {
ParamBuffer.append(parameters.get(key) + "\r\n"); for (String key : parameters.keySet()) {
} ParamBuffer.append("--" + BOUNDARY + "\r\n");
} ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
String ParamBufferString = ParamBuffer.toString(); ParamBuffer.append("\r\n");
data.add(ParamBufferString.getBytes()); ParamBuffer.append(parameters.get(key) + "\r\n");
if (attachments != null) { }
for (String name : attachments.keySet()) { }
StringBuffer FileBuffer = new StringBuffer(); String ParamBufferString = ParamBuffer.toString();
File file = attachments.get(name); data.add(ParamBufferString.getBytes());
FileBuffer.append("--" + BOUNDARY + "\r\n"); if (attachments != null) {
FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" for (String name : attachments.keySet()) {
+ file.getName() + "\"" + "\r\n"); StringBuffer FileBuffer = new StringBuffer();
FileBuffer.append("Content-Type:" + contentType + "" + "\r\n"); File file = attachments.get(name);
FileBuffer.append("\r\n"); FileBuffer.append("--" + BOUNDARY + "\r\n");
String FileBufferString = FileBuffer.toString(); FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
data.add(FileBufferString.getBytes()); + file.getName() + "\"" + "\r\n");
data.add(file); FileBuffer.append("Content-Type:" + contentType + "" + "\r\n");
String FileEnd = "\r\n"; FileBuffer.append("\r\n");
data.add(FileEnd.getBytes()); String FileBufferString = FileBuffer.toString();
} data.add(FileBufferString.getBytes());
} data.add(file);
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n"); String FileEnd = "\r\n";
String EndBufferString = EndBuffer.toString(); data.add(FileEnd.getBytes());
data.add(EndBufferString.getBytes()); }
connection = createConnection(requestUrl, null); }
connection.setRequestMethod("POST"); StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
connection.setRequestProperty("Accept-Charset", "utf-8"); String EndBufferString = EndBuffer.toString();
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); data.add(EndBufferString.getBytes());
connection.setRequestProperty("Content-Length", String.valueOf(data.length())); connection = createConnection(requestUrl, null);
if (headers != null) { connection.setRequestMethod("POST");
for (String key : headers.keySet()) { connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty(key, headers.get(key)); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
} connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
} if (headers != null) {
connection.setDoOutput(true); for (String key : headers.keySet()) {
OutputStream out = connection.getOutputStream(); connection.setRequestProperty(key, headers.get(key));
out.write(data.bytes()); }
out.close(); }
return responseBody(connection); connection.setDoOutput(true);
} catch (Exception e) { OutputStream out = connection.getOutputStream();
throw new RuntimeException(e); out.write(data.bytes());
} finally { out.close();
connection.disconnect(); return responseBody(connection);
} } catch (Exception e) {
} throw new RuntimeException(e);
} finally {
static class Data { connection.disconnect();
}
private byte[][] ds = new byte[0][0]; }
public void add(File file) throws IOException { static class Data {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); private byte[][] ds = new byte[0][0];
byte[] b = new byte[1000];
int n; public void add(File file) throws IOException {
while ((n = fis.read(b)) != -1) { FileInputStream fis = new FileInputStream(file);
bos.write(b, 0, n); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
} byte[] b = new byte[1000];
fis.close(); int n;
bos.close(); while ((n = fis.read(b)) != -1) {
add(bos.toByteArray()); bos.write(b, 0, n);
} }
fis.close();
public void add(byte[] data) { bos.close();
int length = ds.length; add(bos.toByteArray());
byte[][] ds_tmp = new byte[length + 1][]; }
for (int i = 0; i < length; i++) {
ds_tmp[i] = ds[i]; public void add(byte[] data) {
} int length = ds.length;
ds_tmp[length] = data; byte[][] ds_tmp = new byte[length + 1][];
ds = ds_tmp; for (int i = 0; i < length; i++) {
} ds_tmp[i] = ds[i];
}
public int length() { ds_tmp[length] = data;
int length = 0; ds = ds_tmp;
for (byte[] b : ds) { }
length += b.length;
} public int length() {
return length; int length = 0;
} for (byte[] b : ds) {
length += b.length;
public byte[] bytes() { }
byte[] bytes = new byte[length()]; return length;
int index = 0; }
for (int i = 0; i < ds.length; i++) {
for (int k = 0; k < ds[i].length; k++) { public byte[] bytes() {
bytes[index++] = ds[i][k]; byte[] bytes = new byte[length()];
} int index = 0;
} for (int i = 0; i < ds.length; i++) {
return bytes; for (int k = 0; k < ds[i].length; k++) {
} bytes[index++] = ds[i][k];
} }
}
} return bytes;
}
}
}
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