Java工具类--http请求-post

该篇文章详细描述了如何在Java中使用HttpPost发送HTTP请求,包括设置URL、超时时间、Content-Type(如JSON、XML),以及处理不同格式的请求体,同时提及了字符编码的管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

支持各类型报文与参数说明

说明:

  • url : 地址
  • timeout:超时时间 如3秒 3*1000
  • contentType:类型 如
    • application/x-www-form-urlencoded 
    • application/json
    • application/xml
  • requestBody:报文内容 如 
    • application/x-www-form-urlencoded时 为 "key=value&key2=value2"
    • application/json时 为 " \"key\":\"value\",  \"key2\":\"value2\" "
    • application/xml时 为 "<?xml version=\"1.0\" encoding=\"utf-8\" ?><request>" + "<head>" + str_head + "</head>" + "<body>" + str_body + "</body>" + "</request>"
  • encoding:字符编码 如 utf-8

    public static String postJsonBody(String url, int timeout, String contentType, String requestBody, String encoding){
        HttpPost post = new HttpPost(url);
        try {
            post.setHeader("Content-type", contentType);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setConnectionRequestTimeout(timeout)
                    .setExpectContinueEnabled(false).build();
            post.setConfig(requestConfig);

            post.setEntity(new StringEntity(requestBody, encoding));
            logger.info("[HttpUtils Post] begin invoke url:" + url + " , params:" + requestBody);
            CloseableHttpResponse response = httpclient.execute(post);
            try {
                HttpEntity entity = response.getEntity();
                try {
                    if(entity != null){
                        String str = EntityUtils.toString(entity, encoding);
                        logger.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+str);
                        return str;
                    }
                } finally {
                    if(entity != null){
                        entity.getContent().close();
                    }
                }
            } finally {
                if(response != null){
                    response.close();
                }
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException", e);
        } catch (Exception e) {
            logger.error("Exception", e);
        } finally {
            post.releaseConnection();
        }
        return "";
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShyTan

喜欢的给点打赏呗,纯手打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值