Http发送Json请求示例

我们知道目前有很多优秀的大名鼎鼎的http开源框架可以实现任何形式的http调用,在多年的开发经验中我都有使用过。比如apache的httpClient包,非常优秀的Okhttp,jersey client。
而Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率

引入如下依赖:

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.7</version>
        </dependency>

代码示例:

构造JSON参数:

JSONObject param = JSONUtil.createObj();
 param.putOpt(column,value);

hutool工具的链式调用示例:

       String result = HttpUtil.createPost(url)
                .header(Header.CONTENT_TYPE, "application/json")
                .header("appId", "xx")
                .timeout(60000)
                .body(param.toString()).execute().body();

对比下使用原始方式,以下是一个封装示例:

 /**
     * 发送json 请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String postWithJson(String url, String json) {
        String returnValue = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("appId", "ZICXCRkUTBeNcP2eRfCnVQ");
            httpPost.setEntity(requestEntity);
            returnValue = httpClient.execute(httpPost, responseHandler);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }

它非常好用,小巧快捷,类型特别全,简直开发神器。更多学习内容参考官网介绍:https://hutool.cn/
除此之外,另外一个优秀的 开源框架可以提供参考:https://gitee.com/dt_flys/forest 它能屏蔽不同细节http api所带来的所有差异,能通过简单的配置像调用rpc框架一样的去完成极为复杂的http调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值