java实现http post 请求

1.构建Post请求

    public JSONObject getHttpInfo(Param param) {
        HttpPost httpPost;
        try {
            httpPost = new HttpPost("");
            StringEntity stringEntity = new StringEntity(JSON.toJSONString(param), StandardCharsets.UTF_8);
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            throw new BusinessException("genPost error" + e.getMessage());
        }
        return getHttpResponse(httpPost);
    }

2.获取请求结果

    private JSONObject getHttpResponse(HttpUriRequest request) {
        CloseableHttpClient httpClient;
        try {
            SSLContext sslContext = SSLContexts.custom()
                    .loadTrustMaterial(null, (X509Certificate[] x509Certificates, String s) -> true).build();
            //创建httpClient
            httpClient = HttpClients.custom().setRedirectStrategy(new LaxRedirectStrategy())
                    .setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
            CloseableHttpResponse httpResponse = httpClient.execute(request);
            //此处可设置解码方式
            BufferedReader reader = IoUtil.getUtf8Reader(httpResponse.getEntity().getContent());
            String inputLine;
            StringBuilder stringBuffer = new StringBuilder();
            while ((inputLine = reader.readLine()) != null) {
                stringBuffer.append(inputLine);
            }
            reader.close();
            JSONObject respResult = JSONObject.parseObject(stringBuffer.toString());

            return respResult ;
        } catch (Exception e) {
            throw new BusinessException("Http请求失败" + e.getMessage());
        }
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值