post请求接口工具类

12 篇文章 0 订阅
7 篇文章 0 订阅

post请求接口工具类

直接上代码:

// 发送POST请求(url为接口地址,pushData是json字符串,该请求参数会传入在请求body中)
   private static final String MEDIA_TYPE_FORM = "application/x-www-form-urlencoded";
    public static String post(String url, String pushData) throws Exception {
        log.info("=======数据参数=======:" + pushData);
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        HttpPost httpPost = new HttpPost(path);
        //装填参数
        StringEntity s = new StringEntity(pushData, "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                MEDIA_TYPE_FORM));
        //设置参数到请求对象中
        httpPost.setEntity(s);
        //设置header信息
        httpPost.setHeader("Content-type", "application/json");
//        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpPost);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        int status = response.getStatusLine().getStatusCode();
        log.info("==调取接口返回状态码:" + status);
        if (status >= HttpStatus.SC_MULTIPLE_CHOICES) {
            body = "404" + EntityUtils.toString(entity, "utf-8");
        } else {
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "utf-8");
            }
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Java大表哥

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值