post,httpClientpost请求

该博客介绍了如何在项目中使用HttpClient进行POST请求,将参数封装成JSON字符串并发送到第三方接口。通过创建HttpClient实例,构建HttpPost请求,设置请求头和请求体,然后执行请求并获取响应。如果响应状态码为200,则解析响应内容。整个过程展示了HTTP客户端的基本用法和JSON数据交互。

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

项目中使用httpclient进行写post请求

项目中使用过调用第三方接口,将参数封装进行post发送

resJson = HttpClient.doPost(requestUrl, JSON.toJSONString(baseEntity));

地址以及请求的参数实体

public class HttpClient {

    public static String doPost(String url, String jsonString) {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(url);
        //User user = new User();
        //user.setName("潘晓婷");
        //user.setAge(18);
        //user.setGender("女");
        //user.setMotto("姿势要优雅~");
        //String jsonString = JSON.toJSONString(user);

        // 响应模型
        CloseableHttpResponse response = null;
        try {
            StringEntity entity = new StringEntity(jsonString, "UTF-8");

            // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
            httpPost.setEntity(entity);

            httpPost.setHeader("Content-Type", "application/json;charset=utf8");

            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();

            System.out.println("响应状态为:" + response.getStatusLine());
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String res = EntityUtils.toString(responseEntity);
                return res;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

}

之后对返回参数进行解析

JSONObject res = JSON.parseObject(resJson);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值