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);
本文介绍了如何利用HttpClient库发送POST请求,并且处理返回的JSON格式响应数据。首先创建HttpClient对象,然后设置请求头为'Content-Type: application/json;charset=UTF-8',接着将参数转化为JSON字符串,通过StringEntity设置到HttpPost对象中。最后执行请求,获取响应内容并进行UTF-8解码,转换为JSONObject进行解析。
712

被折叠的 条评论
为什么被折叠?



