httpclient的post請求並處理json格式響應資料
HttpClient client = new HttpClient();
form表單提交資料:
PostMethod post = new PostMethod(具體的url); post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); NameValuePair[] param = { new NameValuePair("postid",expressNum), new NameValuePair("type",expressCompany) }; post.setRequestBody(param); post.releaseConnection(); client.executeMethod(post); //處理json串 String response = post.getResponseBodyAsString(); JSONObject jsonStr = JSONObject.fromObject(response); JSONArray jsonArray = jsonStr.getJSONArray("data"); //迴圈新增到infolist中 if (jsonArray!=null&&jsonArray.size()>0) { for (int i=0;i<jsonArray.size();i++) { LogisticsInfoVO v=new LogisticsInfoVO(); JSONObject jsonObject = jsonArray.getJSONObject(i); v.setArriveTime(DateUtils.StringToDate(jsonObject.get("time").toString(),"yyyy-MM-dd HH:mm:ss")); v.setArriveAddress(jsonObject.getString("location")); v.setCurrentRemark(jsonObject.getString("context")); infoList.add(v); }
json格式提交資料:
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
String password= "";//密碼,MD5加密
Map<String,Object> paramMap = new HashMap<String, Object>();
paramMap.put("account", account);
paramMap.put("password", password);
Gson gson = new Gson();
String parameter = gson.toJson(paramMap);
StringEntity se = new StringEntity(parameter,Charset.forName("UTF-8"));//解決請求引數亂碼
se.setContentType("text/json");
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");//解決響應亂碼
JSONObject jsonResult = JSONObject.fromObject(result);