request body的傳值與取值

前言

最近在對接第三方接口,對方採用的是一種不常見的傳遞參數方式,直接將參數轉成json字符串{"param1":value1,"param2":value2},放在request body中進行傳遞,一般是key=value的傳遞形式,業務參數轉成json後,也會有一個總參數json={"param1":value1,"param2":value2},或者是採用rest風格,直接在URI中api.example.com/test/{"param1":value1,"param2":value2},這樣後臺取值也就方便的多。java

HTTP中的兩種傳遞參數的形式,一種就是採用key=value的格式進行傳遞,另外一個直接將數據放在body中進行傳遞,常見於傳遞json字符串或者xml數據流(微信公衆號裏就有采用傳遞XML數據的形式)等,第二種傳遞方式須要用POST方法,不然服務端將取不到數據。json

下面是採用request body形式傳遞參數的實例。api

實例說明

  1. 數據格式:JSON字符串
  2. 工具類:HttpClient
  3. 工具類版本:4.5
  4. 請求方法:POST

客戶端實現

public static void main(String[] args) {
	Map<String,String> map=new HashMap<String,String>();
	map.put("param1", "1");
	map.put("param2", "2");
	map.put("param3", "3");
		
	HttpClient client = HttpClients.createDefault();
	HttpPost post = new HttpPost("http://127.0.0.1:8080/test/test"); 
	try{
	    /*設置參數*/
	    post.setEntity(new StringEntity(JsonMapper.toJsonString(map), "UTF-8"));
	    HttpResponse response = client.execute(post);  
	    HttpEntity entity=response.getEntity();  
	    String returnMsg=EntityUtils.toString(entity,"UTF-8");
	    System.out.println(returnMsg);
	}catch (Exception e) {
		e.printStackTrace();
    }finally{
        /*釋放連接*/
        post.releaseConnection();
    }
}

客戶端中須要把原先key=value參數傳遞形式換成String格式數據傳遞。微信

原先傳參代碼:app

Map<String,String> paramMap=new HashMap<String,String>();
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(String key:paramMap.keySet()){
	params.add(new BasicNameValuePair(key, paramMap.get(key)));
}
UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(params,"UTF-8");
/*設置參數*/
post.setEntity(urlEncodedFormEntity);

如今傳參代碼:工具

Map<String,String> paramMap=new HashMap<String,String>();
/*設置參數*/
post.setEntity(new StringEntity(JsonMapper.toJsonString(paramMap), "UTF-8"));

客戶端輸出結果

服務端實現

@RequestMapping("/test")
public Object Test(HttpServletRequest request){
	InputStream inputStream=null;
	Reader input = null;
	Writer output = new StringWriter();
	try {
		inputStream=request.getInputStream();
		input = new InputStreamReader(inputStream);
        char[] buffer = new char[1024*4];
        int n = 0;
        while(-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        System.out.println(output);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return "請求成功,服務端獲取到的數據爲:"+output.toString();
}
相關文章
相關標籤/搜索