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 曲欣亮
...@@ -29,33 +36,74 @@ import com.egolm.common.exception.HttpUrlEncodingException; ...@@ -29,33 +36,74 @@ import com.egolm.common.exception.HttpUrlEncodingException;
* *
*/ */
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 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);
} }
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) 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");
...@@ -72,29 +120,31 @@ public class HttpUtil { ...@@ -72,29 +120,31 @@ public class HttpUtil {
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) 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");
...@@ -118,9 +168,9 @@ public class HttpUtil { ...@@ -118,9 +168,9 @@ public class HttpUtil {
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;
...@@ -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;
} }
...@@ -150,15 +200,15 @@ public class HttpUtil { ...@@ -150,15 +200,15 @@ public class HttpUtil {
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);
...@@ -166,28 +216,30 @@ public class HttpUtil { ...@@ -166,28 +216,30 @@ 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()]));
} }
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 : (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=");
...@@ -199,28 +251,29 @@ public class HttpUtil { ...@@ -199,28 +251,29 @@ public class HttpUtil {
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 : (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();
...@@ -235,18 +288,19 @@ public class HttpUtil { ...@@ -235,18 +288,19 @@ 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());
data.add(file); data.add(file);
String FileEnd = "\r\n"; String FileEnd = "\r\n";
data.add(FileEnd.getBytes()); data.add(FileEnd.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));
} }
} }
...@@ -276,53 +329,52 @@ public class HttpUtil { ...@@ -276,53 +329,52 @@ public class HttpUtil {
connection.disconnect(); connection.disconnect();
} }
} }
static class Data { static class Data {
private byte[][] ds = new byte[0][0]; private byte[][] ds = new byte[0][0];
public void add(File file) throws IOException { public void add(File file) throws IOException {
FileInputStream fis = new FileInputStream(file); FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000]; byte[] b = new byte[1000];
int n; int n;
while ((n = fis.read(b)) != -1) { while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n); bos.write(b, 0, n);
} }
fis.close(); fis.close();
bos.close(); bos.close();
add(bos.toByteArray()); add(bos.toByteArray());
} }
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;
ds = ds_tmp; ds = ds_tmp;
} }
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;
} }
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];
} }
} }
return bytes; 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