天天看点

贡献一个极简的Post请求发送JSON请求的工作类(亲测有效。其余网上其他都是好多不能用)

一、今天发现了需要用到一个Post,来发送JSON请求的工具类,找了蛮多网上的东西,想找一个简介好用的,一直找不到。那么就自己写一个咯。

二、假设你想发送一个这样的请求:

http.post
{
    "jsonrpc":"2.0",
    "id":int32,
    "method":"Chain33.GenSeed",
    "params":[{"lang":int32}] 
}
           

三、你想收到这样的一个请求

response
{
    "id":int32,
    "result":
    {
        "seed": "fit lava clock valley leisure kit sketch voice venue ski eye apart unfair inch page cannon"
    }
}
           

四、首先需要引入一个包: com.squareup.okhttp3

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>
           

五、首先定义了一个接口

/**
 * @author:wangdong
 * @description:调用区块链那边的Service
 */
public interface BlockchainService {

    /**
     * 调用区块链那边,获取生成公钥和私钥的Seed
     * @return
     */
    String getBlockchainSend();
}           

六、定义一个实现类

@Override
    public String getBlockchainSend() {

        List<Object> list = new ArrayList<>();
        SeedParams seedParams = new SeedParams();
        seedParams.setLang(1);
        list.add(seedParams);
        Map<String, Object> params = new HashMap<>();
        params.put("jsonrpc", "2.0");
        params.put("id", 1);
        params.put("method", "Chain33.GenSeed");
        params.put("params", list);
        String jsonBody = JSONObject.toJSONString(params);

        JSONObject result = httpService.postCall(apiBlockchainervice,jsonBody);
        JSONObject seedDate = (JSONObject) result.get("result");
        return seedDate.get("seed").toString();
    }
}           

七、定义一个postCall接口

package com.gws.utils.webservice;

import com.alibaba.fastjson.JSONObject;

/**
 * @author wangdong
 */
public interface HttpService {

    /**
     * Http服务间调用,Json的请求
     * @param baseUrl
     * @param jsonBody
     * @return
     */
    JSONObject postCall(String baseUrl, String jsonBody);
}
           

八、定义一个postCall的实现类

package com.gws.utils.webservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gws.utils.http.HTTP;
import com.gws.utils.webservice.HttpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * Created by wangdong on 7/18/16.
 */
public class HttpServiceImpl implements HttpService {

    @Autowired
    private HTTP http;

    /**
     * Http服务间调用,Json的请求
     * @param baseUrl
     * @param jsonBody
     * @return
     */
    @Override
    public JSONObject postCall(String baseUrl, String jsonBody) {

        if (StringUtils.isEmpty(baseUrl)){
            throw new IllegalArgumentException("远程调用请求错误,baseUrl不能为空");
        }
        JSONObject jsonObject = null;
        try {
            byte[] bytes =  post(baseUrl, jsonBody);
            return JSON.parseObject(new String(bytes));
        } catch (IOException e) {

        }
        return jsonObject;
    }

}           

九、看一下 byte[] bytes = post(baseUrl, jsonBody);是怎么实现的

/**
     * 
     * POST极简同步方法,JSON内容
     * 
     * @author wangdong 2016年7月17日
     * @param url
     * @param jsonBody
     * @return
     * @throws HttpGwsException
     * @throws IOException
     */
    @Override
    public  byte[] post(String url, String jsonBody) throws HttpGwsException,IOException {
        RequestBody body = RequestBody.create(MEDIA_JSON, jsonBody);
        Request request = new Request.Builder()
                                        .url(url)
                                        .post(body)
                                        .build();
        Response response =ReqExecute(request);
        if (!response.isSuccessful()) {
            throw new HttpGwsException(response,"exception code:" + response.code());
        }
        return response.body().bytes();
    }           

十、RequestBody引用的是com.squareup.okhttp3中的包。

好啦,来测试一些。

最后返回出来的结果:

十一、返回出去

@RequestMapping("getBlockchainSend")
    public JsonResult getBlockchainSend(){

        String result = blockchainService.getBlockchainSend();
        return success(result);
    }           

十二、最终结果

十三、祝大家工作顺利开心。