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

1

parent a6b9a65c
package com.egolm.common;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
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;
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 曲欣亮
* @since 2015-04-01
*
*/
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 {
return HttpUtil.get(requestUrl, parameters, header, null);
}
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;
System.out.println(requestUrl);
connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
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 responseBody(connection);
} catch (Exception e) {
throw new HttpRequestException("HTTP(GET)请求异常", e);
} finally {
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 {
return HttpUtil.post(requestUrl, parameters, headers, null);
}
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 {
HttpURLConnection connection = null;
try {
byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection = createConnection(requestUrl, proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", charset);
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 responseBody(connection);
} catch (Exception e) {
throw new HttpRequestException("HTTP(POST)请求异常", e);
} finally {
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;
try {
bytes = FileUtil.streamToBytes(connection.getInputStream());
} catch (IOException e) {
bytes = FileUtil.streamToBytes(connection.getErrorStream());
}
Map<String, List<String>> responseHeaders = connection.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type");
String responseCharsetName = null;
if (contentTypes != null) {
for (String contentType : contentTypes) {
Matcher matcher = pattern.matcher(contentType);
if (matcher.find()) {
responseCharsetName = matcher.group(3);
break;
}
}
}
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
return new String(bytes, charset);
} else {
return new String(bytes, responseCharsetName);
}
} catch (Exception e) {
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)) {
String[] kv = str.split("=", 2);
List<String> list = map.get(kv[0]);
if (list == null) {
list = new ArrayList<String>();
}
list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null);
map.put(kv[0], list);
}
}
Map<String, String[]> params = new HashMap<String, String[]>();
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()) {
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)));
}
} else {
params.add("sKey=");
}
}
}
return StringUtil.join("&", params);
} catch (UnsupportedEncodingException e) {
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()) {
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 ? "" : sVal));
}
} else {
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) {
HttpURLConnection connection = null;
try {
Data data = new Data();
String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
StringBuffer ParamBuffer = new StringBuffer();
if (parameters != null) {
for (String key : parameters.keySet()) {
ParamBuffer.append("--" + BOUNDARY + "\r\n");
ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
ParamBuffer.append("\r\n");
ParamBuffer.append(parameters.get(key) + "\r\n");
}
}
String ParamBufferString = ParamBuffer.toString();
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("\r\n");
String FileBufferString = FileBuffer.toString();
data.add(FileBufferString.getBytes());
data.add(file);
String FileEnd = "\r\n";
data.add(FileEnd.getBytes());
}
}
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
String EndBufferString = EndBuffer.toString();
data.add(EndBufferString.getBytes());
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()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
out.write(data.bytes());
out.close();
return responseBody(connection);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
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());
}
public void add(byte[] data) {
int length = ds.length;
byte[][] ds_tmp = new byte[length + 1][];
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) {
length += b.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++) {
bytes[index++] = ds[i][k];
}
}
return bytes;
}
}
}
package com.egolm.common;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
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;
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 曲欣亮
* @since 2015-04-01
*
*/
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 {
return HttpUtil.get(requestUrl, parameters, header, null);
}
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;
System.out.println(requestUrl);
connection = createConnection(requestUrl, proxy);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", charset);
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 responseBody(connection);
} catch (Exception e) {
throw new HttpRequestException("HTTP(GET)请求异常", e);
} finally {
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 {
return HttpUtil.post(requestUrl, parameters, headers, null);
}
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 {
HttpURLConnection connection = null;
try {
byte[] bytes = text == null ? new byte[0] : text.getBytes();
connection = createConnection(requestUrl, proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept-Charset", charset);
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 responseBody(connection);
} catch (Exception e) {
throw new HttpRequestException("HTTP(POST)请求异常", e);
} finally {
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;
try {
bytes = FileUtil.streamToBytes(connection.getInputStream());
} catch (IOException e) {
bytes = FileUtil.streamToBytes(connection.getErrorStream());
}
Map<String, List<String>> responseHeaders = connection.getHeaderFields();
List<String> contentTypes = responseHeaders.get("Content-Type");
String responseCharsetName = null;
if (contentTypes != null) {
for (String contentType : contentTypes) {
Matcher matcher = pattern.matcher(contentType);
if (matcher.find()) {
responseCharsetName = matcher.group(3);
break;
}
}
}
if (responseCharsetName == null || responseCharsetName.trim().length() == 0) {
return new String(bytes, charset);
} else {
return new String(bytes, responseCharsetName);
}
} catch (Exception e) {
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)) {
String[] kv = str.split("=", 2);
List<String> list = map.get(kv[0]);
if (list == null) {
list = new ArrayList<String>();
}
list.add(StringUtil.isNotBlank(kv[1]) ? kv[1] : null);
map.put(kv[0], list);
}
}
Map<String, String[]> params = new HashMap<String, String[]>();
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()) {
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)));
}
} else {
params.add("sKey=");
}
}
}
return StringUtil.join("&", params);
} catch (UnsupportedEncodingException e) {
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()) {
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) {
if(StringUtil.isNotEmpty(sVal)) {
System.out.println(sKey+"---"+sVal);
params.add(sKey + "=" +sVal);
}
}
}
/*else {
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) {
HttpURLConnection connection = null;
try {
Data data = new Data();
String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";
StringBuffer ParamBuffer = new StringBuffer();
if (parameters != null) {
for (String key : parameters.keySet()) {
ParamBuffer.append("--" + BOUNDARY + "\r\n");
ParamBuffer.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n");
ParamBuffer.append("\r\n");
ParamBuffer.append(parameters.get(key) + "\r\n");
}
}
String ParamBufferString = ParamBuffer.toString();
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("\r\n");
String FileBufferString = FileBuffer.toString();
data.add(FileBufferString.getBytes());
data.add(file);
String FileEnd = "\r\n";
data.add(FileEnd.getBytes());
}
}
StringBuffer EndBuffer = new StringBuffer("\r\n--" + BOUNDARY + "--\r\n");
String EndBufferString = EndBuffer.toString();
data.add(EndBufferString.getBytes());
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()) {
connection.setRequestProperty(key, headers.get(key));
}
}
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
out.write(data.bytes());
out.close();
return responseBody(connection);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
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());
}
public void add(byte[] data) {
int length = ds.length;
byte[][] ds_tmp = new byte[length + 1][];
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) {
length += b.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++) {
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