版权声明:本文为博主原创文章,未经博主允许不得转载。
这里写个测试用例模拟外部调用,通过httppost 传递一个json封装的表单数据。
包:import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
相关总结:http://xp9802.iteye.com/blog/2123450
每个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转换为对象
logger.info(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());
接收到的字符串:result.toString(): {"goodList":[{"brand":1,"goodsName":"1231213","goods_id":111,"type":1},{"brand":1,"goodsName":"1231213","goods_id":111,"type":1}],"total_record":2}
jsonObject: {"goodList":[{"brand":1,"goodsName":"1231213","goods_id":111,"type":1}, {"brand":1,"goodsName":"1231213","goods_id":111,"type":1}],"total_record":2}
在转换为list对象: Object jsonArray = jsonObject.get("goodList");
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"));测试5:用List<NameValuePair> 封装的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<GoodsInfo> list = JSONObject.parseArray(s1[1],GoodsInfo.class);
这样就能得到一个已list的对象。
综上:传list封装的json要比类封装的json方便,用StringEntity要比List<NameValuePair> 要方便,前者不用再转码和切割字符串。
其他:httpge方式传递数据
如果用url拼接字符串传递数据,那会非常方便,前端不用做任何处理,使用与PHP与Java之间的交互。php只用拼接url就行了。
如:前端url
http://10.118.44.37:8070/teshi-web/supplier/synYxSupplier?supplierName=pl_test3%28%%29&supplierNo=60074&stName=%E4%81&stId=6
后端java 接收
@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";
}
只需要和接口人确认相关字段的键值,然后用spring自动封装,不用request 拿值,这样取得传过来的一个类是非常方便的是非常方便的。
但是不适用与传list对象。