HttpPost传输Json数据并解析
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
HttpPost传输Json数据并解析这⾥写个⽤例模拟外部调⽤,通过httppost 传递⼀个json封装的表单数据。
包:import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
每个json包都不⼀样,这⾥主要是fastjson包的⽤法。
@Test
public void synYxGoodsInfoTest() {
try {
String url = "http://10.118.44.14:8070/teshi-web/goods/synYxGoods";
GoodsInfo goodsInfo = new GoodsInfo();
goodsInfo.setGoods_id(111);
goodsInfo.setGoodsName("1231213");
goodsInfo.setBrand(1);
goodsInfo.setType(1);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String jsonstr = JSON.toJSONString(goodsInfo);
StringEntity se = new StringEntity(jsonstr);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httpPost.setEntity(se);
HttpResponse response=httpClient.execute(httpPost);
//输出调⽤结果
if(response != null && response.getStatusLine().getStatusCode() == 200) {
String result=EntityUtils.toString(response.getEntity());
// ⽣成 JSON 对象
JSONObject obj = JSONObject.parseObject(result);
String errorcode = obj.getString("errorcode");
if("000".equals(errorcode)) {
System.out.println("addHkfishOrder_request_success");
}
}
} catch (Exception e) {
System.out.println("======回不来了=======" );
}
}
控制层接收数据
@RequestMapping(value = "/synYxGoods")
@ResponseBody
public String synYxGoods(HttpServletResponse response,HttpServletRequest request) throws IOException {
//String json = request.getParameter("param"); //这是通过通过get⽅式去url 拼接的键值对,post⽅式取不到值。
request.setCharacterEncoding("UTF-8"); //返回页⾯防⽌出现中⽂乱码
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));//post⽅式传递读取字符流String jsonStr = null;
StringBuilder result = new StringBuilder();
try {
while ((jsonStr = reader.readLine()) != null) {
result.append(jsonStr);
}
} catch (IOException e) {
e.printStackTrace();
}
reader.close();// 关闭输⼊流
JSONObject jsonObject = JSONObject.parseObject(result.toString()); // 取⼀个json转换为对象
(jsonObject);
GoodsInfo goodsInfo = new GoodsInfo();
Date date = new Date();
goodsInfo.setAccess_code1("001");
goodsInfo.setAccess_code1("001");
goodsInfo.setGoodsName(jsonObject.getString("goodsName")); //通过键取到值,再将值封装到类⾥⾯。
goodsInfo.setType(Integer.parseInt(jsonObject.getString("type")));
List<ResultData<String>> data = yxGoodsService.synYxGoodsInfo(goodsInfo);
String json_str = JSON.toJSONString(data);
return write(response, json_str);
}
接收到的字符串:result.toString():{"brand":1,"goodsName":"1231213","goods_id":111,"type":1} JSONObject jsonObject = JSONObject.parseObject(result.toString()); ⽤pareseObject 直接转换为object类
这种⽅式对对⽅只传递⼀个类封装的json字符串,最实⽤。
测试2:⽤StringEntity 封装的json字符串传递⼀个list。
在输⼊端构造⼀个List,⽤list 添加⼏个对象,再转换为json 传过去,接收到的数据与测试1 的差距就是多了⼀个"[ ]" goodsInfoList.add(goodsInfo1);
goodsInfoList.add(goodsInfo2);
goodsInfoList.add(goodsInfo3);
String jsonstr = JSON.toJSONString(list);
接收到的字符串:result.toString():[{"brand":1,"goodsName":"1231213","goods_id":111,"type":1}, {"brand":1,"goodsName":"1231213","goods_id":111,"type":1}]
List<GoodsInfo> list = JSON.parseArray(result.toString(), GoodsInfo.class);//可转换为list的对象。
测试3:⽤StringEntity 封装的json字符串传递⼀个由list封装的类中。
public class GoodsInfoRet {
private List<GoodsInfo> goodList;
private int total_record;
public List<GoodsInfo> getGoodList() {
return goodList;
}
public void setGoodList(List<GoodsInfo> goodList) {
this.goodList = goodList;
}
public int getTotal_record() {
return total_record;
}
public void setTotal_record(int total_record) {
this.total_record = total_record;
}
}
GoodsInfoRet good_dto = new GoodsInfoRet();
good_dto.setGoodList(goodsInfoList);
good_dto.setTotal_record(goodsInfoList.size());
JSONObject jsonObject = JSONObject.parseObject(result.toString());
jsonObject: {"goodList":[{"brand":1,"goodsName":"1231213","goods_id":111,"type":1},
{"brand":1,"goodsName":"1231213","goods_id":111,"type":1}],"total_record":2}
List<GoodsInfo> list = JSON.parseArray(jsonArray+"", GoodsInfo.class); //后⾯⼀定要跟上+,因为转换的是字符串才⾏
得到⼀个list的类,然后再遍历,在循环。
综上,⽤StringEntity se = new StringEntity(jsonstr); 是很有⽤的,能输出正确的代码格式,最后⽅便解析。
测试4:⽤List<NameValuePair> 封装的json字符串传递⼀个由list封装的类中。
String jsonstr = JSON.toJSONString(goodsInfo);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param",jsonstr));
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response=new DefaultHttpClient().execute(httpPost);
接收到的字符串:result.toString() :
param=%7B%22brand%22%3A1%2C%22goodsName%22%3A%221231213%22%2C%22goods_id%22%3A111%2C%22type%22%3A1%7D 这是url 编码,所以需要转码
URLDecoder.decode(result.toString(), "utf-8")
param={"brand":1,"goodsName":"1231213","goods_id":111,"type":1}
这时需要对字符串进⾏⼀个split的处理。
String s = URLDecoder.decode(result.toString(), "utf-8");
String[] s1 = s.split("=");
JSONObject object = JSON.parseObject(s1[1]);
这样就能得到⼀个已object 的对象
⾃⾏封装
goodsInfo.setGoodsName(jsonObject.getString("goodsName"));
封装的json字符串传递⼀个由list封装的list中。
String jsonstr = JSON.toJSONString(goodsInfoList);
转换的是⼀个list对象转换为json字符串,再放在 params 中,
那么接收到的字符串是:
URLDecoder.decode(result.toString(), "utf-8")
param=[{"brand":1,"goodsName":"1231213","goods_id":111,"type":1}]
这时需要对字符串进⾏⼀个split的处理。
String s = URLDecoder.decode(result.toString(), "utf-8");
String[] s1 = s.split("=");
这样就能得到⼀个已list的对象。
综上:传list封装的json要⽐类封装的json⽅便,⽤StringEntity要⽐List<NameValuePair> 要⽅便,前者不⽤再转码和切割字符串。
PHP与之间的交互。
php只⽤拼接url就⾏了。
如:前端url
后端接收
@RequestMapping(value="/totallist")
public String totallist(OrderQuery orderQuery, HttpServletResponse response) {
if(StringUtils.isEmpty(orderQuery.getOrder())) {
orderQuery.setOrder("desc");
}
return query(orderQuery, response);
// return "order/totallist";
}
只需要和接⼝⼈确认相关字段的键值,然后⽤⾃动封装,不⽤request 拿值,这样取得传过来的⼀个类是⾮常⽅便的是⾮常⽅便的。
但是不适⽤与传list对象。