Commit d3e14b38 authored by Quxl's avatar Quxl

x

parent 0b2e1498
......@@ -7,9 +7,12 @@ import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
......@@ -17,11 +20,15 @@ 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.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.egolm.common.exception.HttpRequestException;
import com.egolm.common.exception.HttpResponseException;
import com.egolm.common.exception.HttpUrlEncodingException;
/**
*
* @author 曲欣亮
......@@ -29,33 +36,74 @@ import com.egolm.common.exception.HttpUrlEncodingException;
*
*/
public class HttpUtil {
static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
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 {
return HttpUtil.get(requestUrl, null, null, null);
}
public static String get(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
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);
}
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;
try {
if (requestUrl.startsWith("https")) {
}
String requestBody = HttpUtil.toQueryString(parameters, charset);
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?") + requestBody;
requestUrl = requestUrl + (requestUrl.contains("?") ? (requestUrl.endsWith("&") ? "" : "&") : "?")
+ requestBody;
System.out.println(requestUrl);
URL getUrl = new URL(requestUrl);
connection = (HttpURLConnection) (proxy == null ? getUrl.openConnection() : getUrl.openConnection(proxy));
connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
......@@ -72,29 +120,31 @@ public class HttpUtil {
connection.disconnect();
}
}
public static String post(String requestUrl) throws HttpRequestException {
return HttpUtil.post(requestUrl, null);
}
public static String post(String requestUrl, Map<?, ?> parameters) throws HttpRequestException {
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);
}
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);
}
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;
try {
byte[] bytes = text == null ? new byte[0] : text.getBytes();
URL POST_URL = new URL(requestUrl);
connection = (HttpURLConnection) (proxy == null ? POST_URL.openConnection() : POST_URL.openConnection(proxy));
connection = createConnection(requestUrl, proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
......@@ -118,9 +168,9 @@ public class HttpUtil {
connection.disconnect();
}
}
private static final Pattern pattern = Pattern.compile("charset(\\s+)?=(\\s+)?([0-9a-zA-Z\\-]+)");
public static String responseBody(HttpURLConnection connection) throws HttpResponseException {
try {
byte[] bytes;
......@@ -132,10 +182,10 @@ public class HttpUtil {
Map<String, List<String>> responseHeaders = connection.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type");
String responseCharsetName = null;
if(contentTypes != null) {
for(String contentType : contentTypes) {
if (contentTypes != null) {
for (String contentType : contentTypes) {
Matcher matcher = pattern.matcher(contentType);
if(matcher.find()) {
if (matcher.find()) {
responseCharsetName = matcher.group(3);
break;
}
......@@ -150,15 +200,15 @@ public class HttpUtil {
throw new HttpResponseException("获取HTTP请求响应结果异常", e);
}
}
public static Map<String, String[]> toParameters(String queryString) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
String[] ary = queryString.split("&");
for(String str : ary) {
if(StringUtil.isNotEmpty(str)) {
for (String str : ary) {
if (StringUtil.isNotEmpty(str)) {
String[] kv = str.split("=", 2);
List<String> list = map.get(kv[0]);
if(list == null) {
if (list == null) {
list = new ArrayList<String>();
}
list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null);
......@@ -166,28 +216,30 @@ public class HttpUtil {
}
}
Map<String, String[]> params = new HashMap<String, String[]>();
for(String key : map.keySet()) {
List<String> list = map.get(key);
for (String key : map.keySet()) {
List<String> list = map.get(key);
params.put(key, list.toArray(new String[list.size()]));
}
return params;
}
public static String toQueryString(Map<?, ?> parameters) {
return toQueryString(parameters, null);
}
public static String toQueryString(Map<?, ?> parameters, String encode) throws HttpUrlEncodingException {
try {
List<String> params = new ArrayList<String>();
if(parameters != null) {
for(Object key : parameters.keySet()) {
if (parameters != null) {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null : (val instanceof Object[] ? (Object[])val : new Object[]{val}));
if(sVals != null && sVals.length > 0) {
for(Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode)));
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? ""
: URLEncoder.encode(String.valueOf(sVal), encode == null ? charset : encode)));
}
} else {
params.add("sKey=");
......@@ -199,28 +251,29 @@ public class HttpUtil {
throw new HttpUrlEncodingException("URL编码异常", e);
}
}
public static String formatToQueryString(Map<?, ?> parameters) {
List<String> params = new ArrayList<String>();
if(parameters != null) {
for(Object key : parameters.keySet()) {
if (parameters != null) {
for (Object key : parameters.keySet()) {
Object val = parameters.get(key);
String sKey = String.valueOf(key);
Object[] sVals = (val == null ? null : (val instanceof Object[] ? (Object[])val : new Object[]{val}));
if(sVals != null && sVals.length > 0) {
for(Object sVal : sVals) {
Object[] sVals = (val == null ? null
: (val instanceof Object[] ? (Object[]) val : new Object[] { val }));
if (sVals != null && sVals.length > 0) {
for (Object sVal : sVals) {
params.add(sKey + "=" + (sVal == null ? "" : sVal));
}
} else {
params.add(sKey+"=");
params.add(sKey + "=");
}
}
}
return StringUtil.join("&", params);
}
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers, Map<String, File> attachments,String contentType) {
public static String post(String requestUrl, Map<String, Object> parameters, Map<String, String> headers,
Map<String, File> attachments, String contentType) {
HttpURLConnection connection = null;
try {
Data data = new Data();
......@@ -235,18 +288,19 @@ public class HttpUtil {
}
}
String ParamBufferString = ParamBuffer.toString();
data.add(ParamBufferString.getBytes());
if(attachments != null) {
for(String name : attachments.keySet()) {
data.add(ParamBufferString.getBytes());
if (attachments != null) {
for (String name : attachments.keySet()) {
StringBuffer FileBuffer = new StringBuffer();
File file = attachments.get(name);
FileBuffer.append("--" + BOUNDARY + "\r\n");
FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" + "\r\n");
FileBuffer.append("Content-Type:"+contentType+"" + "\r\n");
FileBuffer.append("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
+ file.getName() + "\"" + "\r\n");
FileBuffer.append("Content-Type:" + contentType + "" + "\r\n");
FileBuffer.append("\r\n");
String FileBufferString = FileBuffer.toString();
data.add(FileBufferString.getBytes());
data.add(file);
data.add(file);
String FileEnd = "\r\n";
data.add(FileEnd.getBytes());
}
......@@ -254,14 +308,13 @@ public class HttpUtil {
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
String EndBufferString = EndBuffer.toString();
data.add(EndBufferString.getBytes());
URL url = new URL(requestUrl);
connection = (HttpURLConnection)url.openConnection();
connection = createConnection(requestUrl, null);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
if(headers != null) {
for(String key : headers.keySet()) {
if (headers != null) {
for (String key : headers.keySet()) {
connection.setRequestProperty(key, headers.get(key));
}
}
......@@ -276,53 +329,52 @@ public class HttpUtil {
connection.disconnect();
}
}
static class Data {
private byte[][] ds = new byte[0][0];
public void add(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
add(bos.toByteArray());
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
add(bos.toByteArray());
}
public void add(byte[] data) {
int length = ds.length;
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[length] = data;
ds = ds_tmp;
}
public int length() {
int length = 0;
for(byte[] b : ds) {
for (byte[] b : ds) {
length += b.length;
}
return length;
return length;
}
public byte[] bytes() {
byte[] bytes = new byte[length()];
int index = 0;
for(int i = 0; i < ds.length; i++) {
for(int k = 0; k < ds[i].length; k++) {
for (int i = 0; i < ds.length; i++) {
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