使用OkHttpClient处理json请求处理的方式

今天遇到一个问题,重构老系统时,前端传递的参数是一个json,controller层可以用@ResponseBody来接收。
因为新系统用的是spring cloud这一套,调用其他服务使用的是feign的形式,找了一圈没有找到合适的方案,于是用OkHttpClient来处理了,这里做个记录。(仍相信feign也能处理,但是刚上手spring cloud,很多都还不是很熟,这里备注作为自己todo的事项)

先看看参数格式:
799093-20180531205223699-2088404554.png

再看看controller层:
799093-20180531205303488-764595548.png

这里使用@RequestBody就可以直接接收到了,后面就直接铺上OKHttpClient的解决代码:

public String createBatch(String jsonString, String url) {
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, jsonString);
        Request requestPost = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        String result = null;
        try {
            response = client.newCall(requestPost).execute();
            if (response.body() != null) {
                result = response.body().string();
            }
        } catch (IOException e) {
            throw new WebCatException(500, e.getMessage());
        }

        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            result = jsonObject.getString("data");
        }

        return result;
    }

参考:https://blog.csdn.net/zhan10001/article/details/78461143

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值