使用HttpClient调用url以及使用HttpURLConnection调用url

本文介绍了如何使用Java的HttpURLConnection和HttpClient库来调用URL。首先讲解了HttpURLConnection的基本用法,接着详细阐述了HttpClient的调用过程。

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

1、使用HttpURLConnection调用url

public static String postJson(String callbackUrl, Map params, int connectTimeout, int readTimeout) {
        String result = "";
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader = null;
        String json = JSON.toJSONString(params);
        try {
            URL url = new URL(callbackUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(connectTimeout);
            httpURLConnection.setReadTimeout(readTimeout);
            httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(json.getBytes("utf-8"));
            os.flush();
            os.close();
            if (httpURLConnection.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream())
                );
                String data = "";
                StringBuilder builder = new StringBuilder();
                while ((data = reader.readLine()) != null) {
                    builder.append(data);
                }
                result = builder.toString();
            }
        } catch (Exception e) {
            log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + params, e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

2、HttpClient调用

public static String postJson2(String callbackUrl, CallBackDTO callBackDTO, int connectTimeout, int readTimeout){
        String jsonString = JSON.toJSONString(callBackDTO);
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(callbackUrl);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
                .setSocketTimeout(readTimeout).build();
        httpPost.setConfig(requestConfig);
        StringEntity stringEntity = null;
        CloseableHttpResponse response = null;
        String res = null;
        try {
            stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity httpEntity = null;
            httpEntity = response.getEntity();
            res = EntityUtils.toString(httpEntity, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
            e.printStackTrace();
        } catch (IOException e) {
            log.error("调用接口[" + callbackUrl + "]失败!请求URL:" + callbackUrl + ",参数:" + callBackDTO, e);
            e.printStackTrace();
        } finally{
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值