java http工具類和HttpUrlConnection上傳文件分析
利用java中的HttpUrlConnection上傳文件,我們其實只要知道Http協議上傳文件的標準格式。那么就可以用任何一門語言來模擬瀏覽器上傳文件。下面有幾篇文章從http協議入手介紹了java中上傳文件.
下面分享一個自己封裝的http工具類(暫不直接支持文件上傳)------沒有引入任何地三方jar包
1 HttpRequest類
package com.yy.game.risecloud.sdk.common.model;
import java.util.Map;
/**
* http請求類
*
* @author zhuhui
*
*/
public class HttpRequest {
/**
* http請求編碼,默認UTF-8
*/
public String charsetName = RisecloudSdkConstant.CHARSET_NAME;
/**
* HTTP請求超時時間,默認5000ms
*/
public int timeout = RisecloudSdkConstant.HTTP_REQUEST_TIMEOUT;
/***
* http請求url地址
*/
public String url;
/***
* http請求方法,只支持GET,POST,PUT,DELETE
*/
public HttpMethod method;
/***
* http請求消息報頭
*/
public Map<String, String> headers;
/**
* http請求url參數
*/
public Map<String, String> params;
/***
* http請求正文內容
*/
public String content;
public HttpRequest() {
}
public HttpRequest(String url, HttpMethod method) {
this.url = url;
this.method = method;
}
public HttpRequest(String url, HttpMethod method, Map<String, String> headers) {
this(url, method);
this.headers = headers;
}
public HttpRequest(String url, HttpMethod method, Map<String, String> headers, Map<String, String> params) {
this(url, method, headers);
this.params = params;
}
public HttpRequest(String url, HttpMethod method, Map<String, String> headers, String content) {
this(url, method, headers);
this.content = content;
}
}
2. HttpResponse類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.yy.game.risecloud.sdk.common.model;
/**
* http響應類
* @author zhuhui
*
*/
public class HttpResponse {
/**
* http響應狀態碼
*/
public int code;
/**
* 與響應代碼一起返回的 HTTP 響應消息
*/
public String message;
/**
* 響應正文內容
*/
public String content;
public HttpResponse(int code, String message, String content) {
this.code = code;
this.message = message;
this.content = content;
}
}2. HttpResponse類
package com.yy.game.risecloud.sdk.common.model;
/**
* http響應類
* @author zhuhui
*
*/
public class HttpResponse {
/**
* http響應狀態碼
*/
public int code;
/**
* 與響應代碼一起返回的 HTTP 響應消息
*/
public String message;
/**
* 響應正文內容
*/
public String content;
public HttpResponse(int code, String message, String content) {
this.code = code;
this.message = message;
this.content = content;
}
} 3.用到的工具方法(可能直接拷貝有問題,去掉出錯的代碼就可以了)package com.yy.game.risecloud.sdk.common.internal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import com.yy.game.risecloud.sdk.common.model.RisecloudSdkConstant;
/**
* 常用工具類
*
* @author zhuhui
*/
public class CommonUtil {
private CommonUtil() {
}
/**
* 判斷字符串是否為空
*
* @param s
* @return 如果字符串為空或者字符串去除首尾空格為空字符串則返回true,反之返回false
*/
public static boolean isEmpty(String s) {
if (s == null || s.trim().length() == 0) {
return true;
}
return false;
}
/**
* 判斷map是否為空
*
* @param map
* map對象
* @return 如果map==null或者map.size()==0則返回true,反之返回false
*/
@SuppressWarnings("all")
public static boolean isEmpty(Map map) {
if (map == null || map.size() == 0) {
return true;
}
return false;
}
/***
* 判斷list是否為空
*
* @param list
* list對象
* @return 如果list==null或者list.size==則返回true,反之返回false
*/
@SuppressWarnings("all")
public static boolean isEmpty(List list) {
if (list == null || list.size() == 0) {
return true;
}
return false;
}
/**
* 將map轉成http url請求參數的格式
*
* @param map
* @return map為空返回null,反之返回類似name=zhangsan&age=14的這樣的格式
*/
public static String map2UrlParams(Map<String, String> map) {
if (isEmpty(map)) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : map.entrySet()) {
if (!isEmpty(entry.getValue())) {
String key = entry.getKey();
try {
String value = URLEncoder.encode(entry.getValue(), "UTF-8");
sb.append("&" + key + "=" + value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (sb.length() > 0) {
return sb.substring(1);
}
return null;
}
public static String uuid() {
return UUID.randomUUID().toString();
}
public static String deleteWhitespace(String str) {
if (isEmpty(str)) {
return str;
}
int sz = str.length();
char[] chs = new char[sz];
int count = 0;
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
chs[count++] = str.charAt(i);
}
}
if (count == sz) {
return str;
}
return new String(chs, 0, count);
}
public static Map<String, String> auth(String token) {
Map<String, String> header = new HashMap<String, String>();
header.put(RisecloudSdkConstant.HEAD_X_AUTH_TOKEN, token);
return header;
}
}4 HttpMethod
package com.yy.game.risecloud.sdk.common.model;
/**
* http請求方法枚舉類
*
* @author zhuhui
*
*/
public enum HttpMethod {
GET, POST, PUT, DELETE;
}5 HttpUtil類 package com.yy.game.risecloud.sdk.common.internal;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.yy.game.risecloud.sdk.common.model.HttpMethod;
import com.yy.game.risecloud.sdk.common.model.HttpRequest;
import com.yy.game.risecloud.sdk.common.model.HttpResponse;
public class HttpUtil {
private HttpUtil() {
}
static HostnameVerifier sslHostnameVerifier;
static synchronized void initSslHostnameVerifier() {
if (sslHostnameVerifier != null) {
return;
}
sslHostnameVerifier = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return urlHostName != null && urlHostName.equals(session.getPeerHost());
}
};
}
static SSLSocketFactory sslSocketFactory;
/**
* 忽略SSL證書
*/
static synchronized void initSslSocketFactory() {
if (sslSocketFactory != null) {
return;
}
InputStream in = null;
try {
SSLContext context = SSLContext.getInstance("TLS");
final X509TrustManager trustManager = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
context.init(null, new TrustManager[] { trustManager }, null);
sslSocketFactory = context.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static HttpURLConnection createConnection(String url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
if ("https".equalsIgnoreCase(url.substring(0, 5))) {
if (sslSocketFactory == null) {
initSslSocketFactory();
}
((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
if (sslHostnameVerifier == null) {
initSslHostnameVerifier();
}
((HttpsURLConnection) conn).setHostnameVerifier(sslHostnameVerifier);
}
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Connection", "close");
return conn;
}
public static HttpResponse execute(HttpRequest request) throws Exception {
/* 參數檢查 */
if (request == null) {
throw new IllegalArgumentException("HttpRequest must be not null");
}
if (CommonUtil.isEmpty(request.url)) {
throw new IllegalArgumentException("HttpRequest url must be not null");
}
if (request.timeout < 0) {
throw new IllegalArgumentException(String.format("timeout=[%s],HttpRequest timeout must be Greater than zero", request.timeout + ""));
}
if (request.method == HttpMethod.GET && !CommonUtil.isEmpty(request.content)) {
throw new IllegalArgumentException("When Http Method is GET,the HttpRquest content must be null");
}
HttpURLConnection connection = null;
String url = request.url;
try {
// 設置url傳遞參數
if (!CommonUtil.isEmpty(request.params)) {
String queryString = CommonUtil.map2UrlParams(request.params);
if (!CommonUtil.isEmpty(queryString)) {
url = url + "?" + queryString;
}
}
// 獲取連接
connection = createConnection(url);
connection.setRequestMethod(request.method.toString());
connection.setConnectTimeout(request.timeout);
connection.setDoOutput(true);
connection.setDoInput(true);
// 設置請求頭
if (!CommonUtil.isEmpty(request.headers)) {
for (Map.Entry<String, String> entry : request.headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
// 設置請求正文
if (!CommonUtil.isEmpty(request.content)) {
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(request.content.getBytes(request.charsetName));
out.close();
}
int code = connection.getResponseCode();
String message = connection.getResponseMessage();
StringBuilder result = new StringBuilder();
InputStream in = connection.getErrorStream();
if (in == null) {
in = connection.getInputStream();
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
char[] cbuf = new char[4096];
while (true) {
int len = reader.read(cbuf);
if (len < 0) {
break;
}
result.append(cbuf, 0, len);
}
}
return new HttpResponse(code, message, result.toString());
} catch (Exception e) {
throw e;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}