package cn.com.prac.util; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import cn.com.prac.util.HttpUtil.ReqData.ReqType; import cn.com.prac.util.HttpUtil.RespData.RespType; import com.alibaba.fastjson.JSON; /** * http請求工具(調用第三方接口) * */ public final class HttpUtil { private final static int REQ_EX_CODE = -99 ; private final static int TIME_OUT = 10 * 10000000; // 超時時間 private HttpUtil(){} public static RespData reqConnection(ReqData reqData){ URL url = null ; BufferedWriter out = null ; BufferedReader reader = null ; HttpURLConnection urlConnection = null ; RespData respData = null ; try { //設置請求參數 StringBuilder arg = null ; String para = "" ; Map<String,Object> parameter = reqData.getParameter() ; if(null != parameter && !parameter.isEmpty()){ arg = new StringBuilder() ; for(Map.Entry<String,Object> entry : parameter.entrySet()){ arg.append(entry.getKey()).append("=").append(entry.getValue()).append("&") ; } para = "?" + arg.substring(0,arg.length()-1) ; } url = new URL(reqData.getUrl() + para) ; urlConnection = (HttpURLConnection) url.openConnection() ; urlConnection.setDoInput(true) ; urlConnection.setDoOutput(true) ; if(0 != reqData.getTimeOut()){ urlConnection.setReadTimeout(reqData.getTimeOut()) ; urlConnection.setConnectTimeout(reqData.getTimeOut()) ; } urlConnection.setRequestMethod(reqData.getMethod().toUpperCase()) ; urlConnection.setRequestProperty("Content-Type",reqData.getContentType()) ; //設置請求頭 Map<String,String> hMap = reqData.getHeader() ; if(null != hMap && !hMap.isEmpty()){ for(Map.Entry<String,String> entry : hMap.entrySet()){ urlConnection.setRequestProperty(entry.getKey(),entry.getValue()) ; } } urlConnection.connect() ; if(ReqType.POST.get().equals(reqData.getMethod()) || ReqType.PUT.get().equals(reqData.getMethod())){ out = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(),Charset.forName("utf-8"))) ; } //設置請求內容(json字符串的請求) String content = reqData.getReqContent() ; if(!isEmpty(content)){ if(null == out){ out = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(),Charset.forName("utf-8"))) ; } out.write(content) ; out.flush() ; } respData = getRespData(reader,urlConnection) ; } catch (MalformedURLException e) { e.printStackTrace(); respData = createRespData(REQ_EX_CODE,"URL不正確。") ; } catch (ProtocolException e) { e.printStackTrace(); respData = createRespData(REQ_EX_CODE,"協議不正確。") ; } catch (IOException e) { e.printStackTrace(); respData = createRespData(REQ_EX_CODE,"數據流讀寫失敗。") ; } finally { close(out) ; close(reader) ; if(null != urlConnection){ urlConnection.disconnect() ; urlConnection = null ; } } return respData ; } private static RespData getRespData(BufferedReader reader,HttpURLConnection urlConnection) throws IOException{ RespData respData = null ; int code = urlConnection.getResponseCode() ; switch (code) { case 200: reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),Charset.forName("utf-8"))) ; String data = null ; StringBuilder result = new StringBuilder() ; while(null !=(data = reader.readLine())){ result.append(data) ; } String resultStr = result.toString() ; try { respData = createRespData(JSON.parse(resultStr)) ; } catch (Exception e) { //返回string:可能是html,xml... respData = createRespData(200,RespType.STRING,resultStr) ; } result.delete(0,result.length()) ; result = null ; break; case 302: respData = createRespData(302,"編碼302:請求定向失敗。") ; break; case 400: respData = createRespData(400,"編碼400:請求出現語法錯誤。") ; break; case 403: respData = createRespData(403,"編碼403:資源不可用。服務器理解客戶的請求,但拒絕處理它。通常由於服務器上文件或目錄的權限設置導致。") ; break; case 404: respData = createRespData(404,"編碼404:無法找到指定位置的資源。") ; break; case 405: respData = createRespData(405,"編碼405:請求方法(GET、POST、HEAD、DELETE、PUT、TRACE等)對指定的資源不適用。") ; break; case 500: respData = createRespData(500,"編碼500:服務器遇到了意料不到的情況,不能完成客戶的請求。") ; break; default: respData = createRespData(code,"請求發生錯誤,錯誤編碼:" + code) ; break ; } return respData ; } /** * 獲取請求參數 * @return */ public static ReqData createReq(){ return createReq(null,null) ; } /** * 獲取請求參數 * @param header 請求頭 * @return */ public static ReqData createReq(Map<String,String> header){ return createReq(header,null) ; } /** * 獲取請求參數 * @param header 請求頭 * @param parameter 請求參數 * @return */ public static ReqData createReq(Map<String,String> header,Map<String,Object> parameter){ return ReqData.create(header,parameter) ; } /** * * @param data 返回的數據結果 * @return */ private static RespData createRespData(Object data){ return createRespData(200,data) ; } /** * * @param code Http返回的狀態 * @param data 請求返回的數據結果 * @return */ private static RespData createRespData(int code,Object data){ return RespData.create(code, data) ; } private static RespData createRespData(int code,RespType respType,Object data){ return RespData.create(code,respType,data) ; } /** * 網絡請求對象 */ public static class ReqData { private ReqData(){} /** * 請求的url */ private String url ; /** * 請求的方式:默認為GET */ private String method = ReqType.POST.get() ; /** * 數據請求類型:默認為application/x-www-form-urlencoded */ private String contentType = "application/x-www-form-urlencoded" ; /** * 數據請求內容:json字符串 */ private String reqContent ; /** * 超時時間設置(單位:毫秒) */ private int timeOut ; /** * 請求參數信息 */ private Map<String,Object> parameter ; /** * 請求頭信息 */ private Map<String,String> header ; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public Map<String, Object> getParameter() { return parameter ; } public Map<String, String> getHeader() { return header; } public int getTimeOut() { return timeOut; } public void setTimeOut(int timeOut) { this.timeOut = timeOut; } public String getReqContent() { return reqContent; } public void setReqContent(String reqContent) { this.reqContent = reqContent; } public ReqData addReqProperty(String key,String value){ if(null == this.header){ this.header = new HashMap<String,String>() ; } this.header.put(key,value) ; return this ; } public ReqData addReqParameter(String key,Object value){ if(null == this.parameter){ this.parameter = new HashMap<String,Object>() ; } this.parameter.put(key,value) ; return this ; } public static ReqData create(){ ReqData reqData = new ReqData() ; return reqData ; } public static ReqData create(Map<String,String> header){ ReqData reqData = create() ; if(null != header && !header.isEmpty()){ reqData.header = header ; } return reqData ; } public static ReqData create(Map<String,String> header,Map<String,Object> parameter){ ReqData reqData = create(header) ; if(null != parameter && !parameter.isEmpty()){ reqData.parameter = parameter ; } return reqData ; } public static enum ReqType{ GET("GET") ,POST("POST") ,PUT("PUT") ,DELETE("DELETE") ; private String type ; private ReqType() { } private ReqType(String type){ this.type = type ; } public String get(){ return this.type ; } } } /** * 請求返回對象 */ public static class RespData{ /** * 請求返回的編碼 */ private int code ; /** * 返回類型:json,string... */ private RespType type ; /** * 請求返回的數據結果 */ private Object data ; private RespData() {} public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public RespType getType() { return type; } public void setType(RespType type) { this.type = type; } public static RespData create(){ return create(200,null) ; } public static RespData create(Object data){ return create(200,data) ; } public static RespData create(int code,Object data){ RespData respData = new RespData() ; respData.setCode(code) ; respData.setData(data) ; respData.setType(RespType.JSON) ; return respData ; } public static RespData create(int code,RespType respType,Object data){ RespData respData = new RespData() ; respData.setCode(code) ; respData.setData(data) ; respData.setType(respType) ; return respData ; } public static enum RespType{ JSON ,STRING ; private String type ; private RespType() {} private RespType(String type){ this.type = type ; } public String get(){ return this.type ; } } } private static boolean isEmpty(String str){ return null == str || "".equals(str.trim()) || "null".equals(str.trim()) ; } private static void close(Closeable stream){ try { if(null != stream){ stream.close() ; } } catch (IOException e) { e.printStackTrace(); } stream = null ; } public static void main(String[] args) { /**********無參數和無請求頭的情況*******************/ /*//創建請求對象 ReqData reqData = HttpUtil.createReq() ; //請求方式 reqData.setMethod("POST") ; //數據請求類型 reqData.setContentType("Application/json") ; //請求地址 reqData.setUrl("http://wx.cqzfj.com/xmy-b2b-app-web/index?v=1.0") ; //調用接口 RespData respData = HttpUtil.reqConnection(reqData) ; //獲得返回的json字符串 String result = JSON.toJSONString(respData) ; System.out.println("獲得的json:" + result) ;*/ /**********帶參數和請求頭的情況*******************/ //創建請求對象 ReqData reqData = HttpUtil.createReq() ; //請求方式 reqData.setMethod("POST") ; //數據請求類型 reqData.setContentType("application/json") ; //參數 reqData.addReqParameter("status",-1) ; reqData.addReqParameter("v","1.0") ; //添加header請求頭信息 reqData.addReqProperty("token","A74DF5F691C24A158A50A2D880284665") ; //請求地址 reqData.setUrl("http://****.com/list") ; //調用接口 RespData respData = HttpUtil.reqConnection(reqData) ; //獲得返回的json字符串 String result = JSON.toJSONString(respData) ; System.out.println("獲得的json:" + result) ; /***********也可以通過這種方式傳header**************/ /*Map<String,String> header = new HashMap<String,String>() ; header.put("token", "A74DF5F691C24A158A50A2D880284665") ; ReqData reqData = HttpUtil.createReq(header) ;*/ } }