1. 程式人生 > >HTTP傳送post、put請求,帶header、body的工具類,附呼叫測試demo

HTTP傳送post、put請求,帶header、body的工具類,附呼叫測試demo

HTTP請求方法(可直接copy至你的工具類,屢試不爽)

import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

/**
 * HTTP傳送post、put請求,帶header、body的方法,獲取結果
 * @param url
 * @param requestMethod POST、PUT
 * @param headerMap
 * @param contentMap
 * @author yswKnight
 * @return
 */
public static String httpRequest(String url, String requestMethod, Map<String, String> headerMap, JSONObject contentMap) { String result = ""; try { URL restURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) restURL.openConnection(); connection.setRequestMethod(requestMethod)
; connection.setDoInput(true); connection.setDoOutput(true); Iterator headerIterator = headerMap.entrySet().iterator(); //迴圈增加header while(headerIterator.hasNext()){ Map.Entry<String,String> elem = (Map.Entry<String, String>) headerIterator.next(); connection.setRequestProperty
(elem.getKey(),elem.getValue()); } OutputStreamWriter outer = null; outer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); outer.write(contentMap.toString()); outer.flush(); outer.close(); InputStream ips = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(ips, "UTF-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); buffer.append("\r\n"); } in.close(); ips.close(); connection.disconnect(); //得到結果 result = buffer.toString(); } catch (IOException e) { e.printStackTrace(); } return result; }

客戶端呼叫程式碼

public static void main(String[] args) {
	try {
		String url = "http://localhost:8090/project/method";
		//封裝請求引數
		//訊息請求頭Headers
		Map<String, String> headersMap = new HashMap<String, String>();
		headersMap.put("Content-Type","application/json; charset=utf-8");
		headersMap.put("appmark","應用標識");
		headersMap.put("sign","加密後的簽名");
		//請求實體body(json格式)
		JSONObject contentMap = new JSONObject();
		contentMap.put("IdCard","3216520000000000218");
		contentMap.put("name","張三");
		String post = HttpClientUtil.httpRequest(url,"PUT", headersMap, contentMap);
		//輸出請求介面獲取的資訊
		System.err.println(post);
	} catch (Exception e) {
		logger.error("HTTP請求異常,原因:"+e.fillInStackTrace());
	}
}