Commit d3e14b38 authored by Quxl's avatar Quxl

x

parent 0b2e1498
...@@ -7,9 +7,12 @@ import java.io.IOException; ...@@ -7,9 +7,12 @@ 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.MalformedURLException;
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.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;
...@@ -17,11 +20,15 @@ import java.util.Map; ...@@ -17,11 +20,15 @@ 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.SSLContext;
import javax.net.ssl.TrustManager;
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 曲欣亮
...@@ -36,6 +43,42 @@ public class HttpUtil { ...@@ -36,6 +43,42 @@ public class HttpUtil {
private static final String charset = "utf-8"; private static final String charset = "utf-8";
private static SSLContext sslContextDefault = null;
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static SSLContext getDefaultSSLContext() {
if (sslContextDefault == null) {
try {
sslContextDefault = SSLContext.getInstance("SSL");
sslContextDefault.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
} catch (Exception e) {
e.printStackTrace();
}
}
return sslContextDefault;
}
private static HttpURLConnection createConnection(String requestUrl, Proxy proxy) throws IOException{
URL HTTP_URL = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) (proxy == null ? HTTP_URL.openConnection() : HTTP_URL.openConnection(proxy));
if (requestUrl.startsWith("https")) {
((HttpsURLConnection) connection).setSSLSocketFactory(getDefaultSSLContext().getSocketFactory());
}
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);
} }
...@@ -44,18 +87,23 @@ public class HttpUtil { ...@@ -44,18 +87,23 @@ public class HttpUtil {
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) throws HttpRequestException { public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header)
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) throws HttpRequestException { public static String get(String requestUrl, Map<?, ?> parameters, Map<String, String> header, Proxy proxy)
throws HttpRequestException {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
if (requestUrl.startsWith("https")) {
}
String requestBody = HttpUtil.toQueryString(parameters, charset); String requestBody = HttpUtil.toQueryString(parameters, charset);
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody; requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?")
+ requestBody;
System.out.println(requestUrl); System.out.println(requestUrl);
URL getUrl = new URL(requestUrl); connection = createConnection(requestUrl, proxy);
connection = (HttpURLConnection) (proxy == null ? getUrl.openConnection() : getUrl.openConnection(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");
...@@ -81,20 +129,22 @@ public class HttpUtil { ...@@ -81,20 +129,22 @@ public class HttpUtil {
return HttpUtil.post(requestUrl, parameters, null); return HttpUtil.post(requestUrl, parameters, null);
} }
public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers) throws HttpRequestException { public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers)
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) throws HttpRequestException { public static String post(String requestUrl, Map<?, ?> parameters, Map<String, String> headers, Proxy proxy)
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) throws HttpRequestException { public static String post(String requestUrl, String text, Map<String, String> headers, Proxy proxy)
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();
URL POST_URL = new URL(requestUrl); connection = createConnection(requestUrl, proxy);
connection = (HttpURLConnection) (proxy == null ? POST_URL.openConnection() : POST_URL.openConnection(proxy));
connection.setDoOutput(true); connection.setDoOutput(true);
connection.setDoInput(true); connection.setDoInput(true);
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
...@@ -132,10 +182,10 @@ public class HttpUtil { ...@@ -132,10 +182,10 @@ public class HttpUtil {
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;
} }
...@@ -154,11 +204,11 @@ public class HttpUtil { ...@@ -154,11 +204,11 @@ public class HttpUtil {
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);
...@@ -166,7 +216,7 @@ public class HttpUtil { ...@@ -166,7 +216,7 @@ public class HttpUtil {
} }
} }
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()]));
} }
...@@ -180,14 +230,16 @@ public class HttpUtil { ...@@ -180,14 +230,16 @@ public class HttpUtil {
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 : (val instanceof Object[] ? (Object[])val : new Object[]{val})); Object[] sVals = (val == null ? null
if(sVals != null && sVals.length > 0) { : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
for(Object sVal : sVals) { if (sVals != null && sVals.length > 0) {
params.add(sKey + "=" + (sVal == null ? "" : URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode))); for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? ""
: URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode)));
} }
} else { } else {
params.add("sKey="); params.add("sKey=");
...@@ -202,25 +254,26 @@ public class HttpUtil { ...@@ -202,25 +254,26 @@ public class HttpUtil {
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 : (val instanceof Object[] ? (Object[])val : new Object[]{val})); Object[] sVals = (val == null ? null
if(sVals != null && sVals.length > 0) { : (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
for(Object sVal : sVals) { if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : sVal)); params.add(sKey + "=" + (sVal == null ? "" : sVal));
} }
} else { } else {
params.add(sKey+"="); params.add(sKey + "=");
} }
} }
} }
return StringUtil.join("&", params); return StringUtil.join("&", params);
} }
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers,
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, Map<String, File> attachments,String contentType) { Map<String, File> attachments, String contentType) {
HttpURLConnection connection = null; HttpURLConnection connection = null;
try { try {
Data data = new Data(); Data data = new Data();
...@@ -236,13 +289,14 @@ public class HttpUtil { ...@@ -236,13 +289,14 @@ public class HttpUtil {
} }
String ParamBufferString = ParamBuffer.toString(); String ParamBufferString = ParamBuffer.toString();
data.add(ParamBufferString.getBytes()); data.add(ParamBufferString.getBytes());
if(attachments != null) { if (attachments != null) {
for(String name : attachments.keySet()) { for (String name : attachments.keySet()) {
StringBuffer FileBuffer = new StringBuffer(); StringBuffer FileBuffer = new StringBuffer();
File file = attachments.get(name); File file = attachments.get(name);
FileBuffer.append("--" + BOUNDARY + "\r\n"); FileBuffer.append("--" + BOUNDARY + "\r\n");
FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" + "\r\n"); FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
FileBuffer.append("Content-Type:"+contentType+"" + "\r\n"); + file.getName() + "\"" + "\r\n");
FileBuffer.append("Content-Type:" + contentType + "" + "\r\n");
FileBuffer.append("\r\n"); FileBuffer.append("\r\n");
String FileBufferString = FileBuffer.toString(); String FileBufferString = FileBuffer.toString();
data.add(FileBufferString.getBytes()); data.add(FileBufferString.getBytes());
...@@ -254,14 +308,13 @@ public class HttpUtil { ...@@ -254,14 +308,13 @@ public class HttpUtil {
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n"); StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
String EndBufferString = EndBuffer.toString(); String EndBufferString = EndBuffer.toString();
data.add(EndBufferString.getBytes()); data.add(EndBufferString.getBytes());
URL url = new URL(requestUrl); connection = createConnection(requestUrl, null);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST"); connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "utf-8"); connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
connection.setRequestProperty("Content-Length", String.valueOf(data.length())); connection.setRequestProperty("Content-Length", String.valueOf(data.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));
} }
} }
...@@ -277,7 +330,6 @@ public class HttpUtil { ...@@ -277,7 +330,6 @@ public class HttpUtil {
} }
} }
static class Data { static class Data {
private byte[][] ds = new byte[0][0]; private byte[][] ds = new byte[0][0];
...@@ -298,7 +350,7 @@ public class HttpUtil { ...@@ -298,7 +350,7 @@ public class HttpUtil {
public void add(byte[] data) { public void add(byte[] data) {
int length = ds.length; int length = ds.length;
byte[][] ds_tmp = new byte[length + 1][]; byte[][] ds_tmp = new byte[length + 1][];
for(int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
ds_tmp[i] = ds[i]; ds_tmp[i] = ds[i];
} }
ds_tmp[length] = data; ds_tmp[length] = data;
...@@ -307,7 +359,7 @@ public class HttpUtil { ...@@ -307,7 +359,7 @@ public class HttpUtil {
public int length() { public int length() {
int length = 0; int length = 0;
for(byte[] b : ds) { for (byte[] b : ds) {
length += b.length; length += b.length;
} }
return length; return length;
...@@ -316,8 +368,8 @@ public class HttpUtil { ...@@ -316,8 +368,8 @@ public class HttpUtil {
public byte[] bytes() { public byte[] bytes() {
byte[] bytes = new byte[length()]; byte[] bytes = new byte[length()];
int index = 0; int index = 0;
for(int i = 0; i < ds.length; i++) { for (int i = 0; i < ds.length; i++) {
for(int k = 0; k < ds[i].length; k++) { for (int k = 0; k < ds[i].length; k++) {
bytes[index++] = ds[i][k]; bytes[index++] = ds[i][k];
} }
} }
......
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