封装HTTP请求

该代码示例展示了在Java中如何使用HttpClient库进行POST请求。两个doPost方法分别处理不同情况的POST请求,设置请求头、内容并执行HTTP操作。toGetInventoryInfo方法进一步演示了如何将请求参数转换为JSON,发送请求,并解析响应结果来获取特定信息。
摘要由CSDN通过智能技术生成

 

/**
     * post请求
     *
     * @param uri
     * @return
     * @throws IOException
     */
public static HttpResponse doPost(String uri, String token) throws IOException {
    // 创建httpClient对象
    HttpClient httpclient = HttpClients.createDefault();
    // 设置请求地址
    HttpPost httppost = new HttpPost(uri);
    // 设置请求头
    httppost.addHeader("Content-Type", HttpConstants.HEADER_CONTENT_TYPE_JSON);
    httppost.addHeader("Authorization", token);
    // 执行http请求
    return httpclient.execute(httppost);
}
/**
     * post请求
     *
     * @param params 参数
     * @param uri uri
     * @return {@link HttpResponse}
     */
 public static HttpResponse doPostReq(String params, String uri) throws IOException {
    // 创建httpClient对象
    HttpClient httpclient = HttpClients.createDefault();
    // 设置请求地址
    HttpPost httppost = new HttpPost(uri);
    // 设置请求头
    httppost.addHeader("Content-Type", HttpConstants.HEADER_CONTENT_TYPE_JSON);
    // 设置请求内容
    StringEntity se = new StringEntity(params, "utf-8");
    httppost.setEntity(se);
    // 执行http请求
    return httpclient.execute(httppost);
}
public final class HttpConstants {
    public static final String HEADER_CONTENT_TYPE_JSON = "application/json;charset=UTF-8";

    public static final Integer SUCCESS_CODE = 200;
    
    public HttpConstants() {}
}
private boolean toGetInventoryInfo(Map<String, Object> reqMap) throws IOException {
        String params = JSON.toJSONStringWithDateFormat(reqMap,
                DateUtil.FORMAT_DATE_TIME
                , SerializerFeature.DisableCircularReferenceDetect);
        String inventoryUrl = aeonProperties.getInventory();
        log.info("请求,params:{},inventoryUrl:{}", params, inventoryUrl);
        HttpResponse response = HttpUtils.doPostReq(params, inventoryUrl);
        log.info("请求结果,response:{}", response.toString());
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            log.info("请求数据结果,result:{}", result);
            List<Map> maps = JSONObject.parseArray(result, Map.class);
            if(!CollectionUtils.isEmpty(maps)){
                Map<String, Object> map = maps.get(0);
               return (Boolean) map.get("isRepertory");
            }
        }else {
            log.info("请求失败,params:{},inventoryUrl:{}", params, inventoryUrl);
        }
        return false;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值