HttpClient 傳送Json請求,結果返回Json
阿新 • • 發佈:2019-01-07
public static JSONObject post(String url,JSONObject json){ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); HttpResponse res = client.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.OK.value()){ HttpEntity entity = res.getEntity(); String charset = EntityUtils.getContentCharSet(entity); response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset))); } } catch (Exception e) { throw new RuntimeException(e); } return response; }
如果你的內容沒有巢狀關係,就全都是ojb.put(key, value);
如果有巢狀關係,就是 subObj=new JSONObject();obj.put(key, subObj);
如果需要陣列,就用JSONArray 物件。
那麼你需要的是:{header:{"code": -100, "message": {"title": "", "detail": ""}},body:{dataStores:{},parameters:{"args": ["menu_jw_pj_xspj_x", ">>"], "responseParam": "tooltip"}}}
這裡面是有巢狀關係的,你先將其格式化,然後就知道巢狀關係了:
JavaScript code ?
1 2 3 4 5 6 7 8 9 10 11 |
{
header : {
"code" : -100, "message" : {
"title" : "" , "detail" : ""
}
}, body : {
dataStores : {}, parameters : {
"args" : [ "menu_jw_pj_xspj_x" , ">>" ], "responseParam" : "tooltip"
}
}
};
|
注意方括號代表陣列。
以前面為例:
JSONObject obj = new JSONObject();
JSONObject objHead = new JSONObject();
obj.put("head", objHead);
objHead.put("code", -100);
JSONObject objMsg = new JSONObject();
objHead.put("message", objMsg);
objMsg.put("title", "");
objMsg.put("detail", "");