Java post 请求封装, 代码粘贴即可使用

Java post 请求封装, 代码粘贴即可使用

/**
 * 发送POST请求
 * obj为请求体,可为空
 * headers为请求头,可为空
 */
public String sendPost(String url, JSONObject obj, Map<String, String> headers) {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String result = "";
    //创建post请求对象
    HttpPost post = new HttpPost(url);
    //遍历请求头,挨个插入请求
    if(headers != null){
        for(String key : headers.keySet()){
            post.addHeader(key, headers.get(key));
        }
    }
    try {
        if(obj != null){
            StringEntity jsonStr = new StringEntity(obj.toJSONString(), Charset.forName("UTF-8"));
            post.setEntity(jsonStr);
        }
        httpClient = HttpClients.createDefault();
        //启动执行请求,并获得返回值
        response = httpClient.execute(post);
        //得到返回的entity对象
        HttpEntity entity = response.getEntity();
        //把实体对象转换为string
        result = EntityUtils.toString(entity, "UTF-8");
        //返回内容
    } catch (Exception e1) {
        e1.printStackTrace();
    } finally {
        // 关闭资源
        if (null != response) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != httpClient) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值