直接上代码
/** * 测试生成json数据 */ @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); }