转自:https://blog.csdn.net/qq_35114086/article/details/52317311

这里写个测试用例模拟外部调用,通过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());

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与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对象。

HttpPost 传输Json数据并解析的更多相关文章

  1. Java:HttpPost 传输Json数据过长使用HttpServletRequest解析

    直接上代码 /** * 测试生成json数据 */ @Test public void synYxGoodsInfoTest() { try { String url = "http://1 ...

  2. Java后台使用httpclient入门HttpPost请求(form表单提交,File文件上传和传输Json数据)

    一.HttpClient 简介 HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 ...

  3. HttpURLConnection从网上获取Json数据并解析详解

    HttpURLConnection从网上获取Json数据并解析 1.HttpURLConnection请求数据的步骤 (1)构造一个URL接口地址: URL url = new URL("h ...

  4. Django之AJAX传输JSON数据

    目录 Django之AJAX传输JSON数据 AJAX 中 JSON 数据传输: django响应JSON类型数据: django 响应 JSON 类型数据: Django之AJAX传输JSON数据 ...

  5. Android 之 json数据的解析(jsonReader)

    json数据的解析相对而言,还是比较容易的,实现的代码也十分简单.这里用的是jsonReade方法来进行json数据解析. 1.在解析之前,大家需要知道什么是json数据. json数据存储的对象是无 ...

  6. iOS开发网络篇—JSON数据的解析

    iOS开发网络篇—JSON数据的解析 iOS开发网络篇—JSON介绍 一.什么是JSON JSON是一种轻量级的数据格式,一般用于数据交互 服务器返回给客户端的数据,一般都是JSON格式或者XML格式 ...

  7. 通过ajax和spring 后台传输json数据

    在通过ajax从页面向后台传数据的时候,总是返回415(Unsupported media type)错误,后台无法获取数据.如下图所示: 在尝试解决这个问题的时候,我们首先要理解一下概念: @req ...

  8. javascript中 json数据的解析与序列化

    首先明确一下概念: json格式数据本质上就是字符串: js对象:JavaScript 中的几乎所有事务都是对象:字符串.数字.数组.日期.函数,等等. json数据的解析: 就是把后端传来的json ...

  9. android基础---->JSON数据的解析

    上篇博客,我们谈到了XML两种常用的解析技术,详细可以参见我的博客(android基础---->XMl数据的解析).网络传输另外一种数据格式JSON就是我们今天要讲的,它是比XML体积更小的数据 ...

随机推荐

  1. AtomicInteger在实际项目中的应用

    AtomicInteger.一个提供原子操作的Integer的类. 在Java语言中,++i和i++操作并非线程安全的.在使用的时候,不可避免的会用到synchronized关键字. 而AtomicI ...

  2. 自己定义UITextField

    目的是实现例如以下的效果: UITextField的leftView是自己定义的UIView,当中: 1.包括一个居中显示的icon.而且上,左,下各有1px的间隙 2.左上和左下是圆角,右边没有圆角 ...

  3. UITableView基础入门

    新建一个Single View Application 添加一个空类如下: using System; using UIKit; using Foundation; namespace BasicTa ...

  4. php 批量删除数据

    php 批量删除数据 :比如我们在看邮箱文件的时候,积攒了一段时间以后,看到有些文件没有用了 这时候我们就会想到把这些 没用的文件删除,这时候就用到了批量删除数据的功能,这里我是用了数据库原有的一个表 ...

  5. 【BZOJ1528】[POI2005]sam-Toy Cars 贪心

    [BZOJ1528][POI2005]sam-Toy Cars Description Jasio 是一个三岁的小男孩,他最喜欢玩玩具了,他有n 个不同的玩具,它们都被放在了很高的架子上所以Jasio ...

  6. 【BZOJ3728】PA2014Final Zarowki 贪心

    [BZOJ3728]PA2014Final Zarowki Description 有n个房间和n盏灯,你需要在每个房间里放入一盏灯.每盏灯都有一定功率,每间房间都需要不少于一定功率的灯泡才可以完全照 ...

  7. mybatis学习总结(三)——增删查改

    映射器是mybatis的基础和核心,下面学习下映射器的使用 映射器的主要元素 select  查询语句,可以自定义参数和返回结果集 insert  插入语句,返回一个整数,代表插入的条数 update ...

  8. 九度OJ 1085:求root(N, k) (迭代)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:1407 解决:523 题目描述: N<k时,root(N,k) = N,否则,root(N,k) = root(N',k).N'为N的 ...

  9. java内存泄露具体解释

    非常多人有疑问,java有非常好的垃圾回收机制,怎么会有内存泄露?事实上是有的,那么何为内存泄露?在Java中所谓内存泄露就是指在程序执行的过程中产生了一些对象,当不须要这些对象时,他们却没有被垃圾回 ...

  10. Mall电商项目总结(一)——项目概述

    项目概述 此电商项目为本人学习项目,后端 使用nginx实现负载均衡转发请求到多台tomcat服务器,使用多台 redis服务器分布式 缓存用户登录信息. 项目已经部署到阿里云服务器,从阿里云linu ...