先上工具類代碼 使用方法在最下面
import com.alibaba.fastjson.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class HttpUtil {
public enum METHOD{
POST("POST"),
GET("GET"),
JSON("application/json;charset=UTF-8"),
URLENCODED("application/x-www-form-urlencoded"),
FORM_DATA("multipart/form-data");
private String value;
public String getValue() {
return value;
}
private METHOD(String value) {
this.value = value;
}
}
private HttpURLConnection connection;//網絡連接對象
public static AtomicInteger timeoutNum = new AtomicInteger();//超時對象
private METHOD type;//請求體數據類型
private final String urlStr;//請求地址
private final StringBuilder param;//請求參數
private final Map<String, String> paramMap;//請求參數
private final Map<String, String> headParam;//請求頭參數
/**
* 初始化HttpUtil
* @param urlStr 請求地址
*/
public HttpUtil(String urlStr) {
this(urlStr,null);
}
/**
* 初始化HttpUtil 傳入參數
* 也可以後續使用setParam添加參數
* @param urlStr 請求地址
* @param paramMap 請求參數
*/
public HttpUtil(String urlStr, Map<String, String> paramMap) {
this.urlStr = urlStr;
this.headParam = new HashMap<String, String>();
if (null == paramMap) this.paramMap = new HashMap<String, String>();
else this.paramMap = paramMap;
this.param = new StringBuilder();
for (String key : paramMap.keySet()) {
param.append(key + "=" + paramMap.get(key) + "&");
}
}
/**
* 按照指定請求方式 初始化請求
* @param method 請求方法 GET OR POST
*/
public void init(METHOD method) {
try{
URL url = null;
switch (method){
case GET:
url = new URL(urlStr + "?" + param.toString());
connection = (HttpURLConnection) url.openConnection();
break;
case POST:
//打開連接
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
break;
}
//設置請求頭
for (String key : headParam.keySet()) {
connection.setRequestProperty(key, headParam.get(key));
}
this.initParameter();
}catch (Exception e){
throw new RuntimeException("HttpURLConnection初始化異常");
}
}
/**
* 獲取請求結果 在init方法後執行
* @return 請求結果
*/
public String result(){
this.checkConnection();
try{
connection.connect();
InputStream input = null;
if (connection.getResponseCode() == 200) {
input = connection.getInputStream();
} else {
input = connection.getErrorStream();
}
return new String(readInputStream(input), "UTF-8");
}catch (Exception e){
throw new RuntimeException("獲取網絡請求結果時發生異常");
}
}
/**
* 初始化POST請求參數
*/
private void initParameter() throws IOException {
String body = "";
//沒有請求體
if (null == type) return;
switch (type){
case URLENCODED:
body = param.toString();
break;
case JSON:
//對象轉JSON 我用的是阿里爸爸的fastjson 你可以用別的
body = JSONObject.toJSONString(paramMap);
break;
case FORM_DATA:
throw new RuntimeException("該類型還未整理");
}
// System.out.println(body);//看看請求體長啥樣
OutputStream out = null;
try{
out = connection.getOutputStream();
out.write(body.getBytes("utf-8"));
out.flush();
}catch (UnknownHostException e){
timeoutNum.incrementAndGet();
throw new RuntimeException("設置網絡請求參數時發生異常");
}catch (SocketTimeoutException e){
timeoutNum.incrementAndGet();
throw new RuntimeException("設置網絡請求參數時發生異常");
}catch (IOException e){
timeoutNum.incrementAndGet();
throw new RuntimeException("設置網絡請求參數時發生異常");
}finally {
if(null != out){
out.close();
}
}
}
/**
* 設置請求頭
* 必須在init方法前執行
* @param head
* @param value
*/
public void setHttpHead(String head, String value){
headParam.put(head, value);
}
/**
* 設置參數
* 必須在init方法前執行
* @param key
* @param value
*/
public void setParam(String key, String value){
paramMap.put(key, value);
param.append(key + "=" + paramMap.get(key) + "&");
}
/**
* 設置請求體格式
* 必須在init方法前執行
* @param head 請求體格式
*/
public void setHttpHead(METHOD head){
switch (head){
case POST:
case GET:
break;
default:
this.type = head;
headParam.put("Content-Type", head.getValue());
}
}
/**
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;
}
/**
* 檢查網絡連接對象是否初始化
*/
public void checkConnection(){
if (null == connection)
throw new RuntimeException("HttpURLConnection未初始化");
}
}
GET方法
//請求參數
Map paramMap = new HashMap();
paramMap.put("aaaa","參數一");
paramMap.put("bbbbb", "參數二");
//創建工具類對象
HttpUtil net = new HttpUtil("請求地址不需要'?'",paramMap);
//按照GET方法初始化
net.init(HttpUtil.METHOD.GET);
//拿到結果
net.result();
POST方法
//請求參數
Map paramMap = new HashMap();
paramMap.put("aaaa","參數一");
paramMap.put("bbbbb", "參數二");
//創建工具類對象
HttpUtil net = new HttpUtil("請求地址不需要'?'",paramMap);
//也可以後續添加參數 需要在init()前
net.setParam("cccc", "參數三");
//設置請求體格式爲application/x-www-form-urlencoded或者application/json
//POST請求必填
net.setHttpHead(HttpUtil.METHOD.URLENCODED);
//可以init前使用setHttpHead設置請求頭 帶上token等參數
net.setHttpHead("token", "123465");
//按照POST方法初始化
net.init(HttpUtil.METHOD.POST);
//拿到結果
net.result();