httpclient的post请求并处理json格式响应数据

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

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 account= "";//用户账号
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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值