CloseableHttpClient发送https请求

本文介绍了如何使用ApacheHttpClient库在Java中发送POST请求到RESTfulAPI,包括设置请求体、编码和处理异常。方法一是使用Gson将对象转换为JSON字符串,方法二是直接使用JSONObject进行请求参数传递。
摘要由CSDN通过智能技术生成

方式一:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.invoke.MethodHandles;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class TestInfrom {

    public static void main(String[] args) throws Exception {
        String requestPath= "https://xxx:xxx/xxx";
        TestReqBean testReqBean = new TestReqBean();
        String json= GsonUtil.getInstance().toJson(testReqBean);
        String res= doPost(requestPath, json,"application/json","utf8");
        TestRespBean data=GsonUtil.getInstance().fromJson(res, TestRespBean.class);
        System.out.println("inform_begin>>requestPath:" + requestPath+",data="+data);

    }
    public static String doPost(String url, String stringJsonPrama, String contentType, String encode) {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        if (null == stringJsonPrama || null == url || null == encode) {
            return "Parameters error";
        }
        try {
            if (null == httpClient)
                httpClient = HttpClients.createDefault();
            if (null == httpPost)
                httpPost = new HttpPost(url);

            // 设置参数
            StringEntity sen = new StringEntity(stringJsonPrama, encode);
            sen.setContentEncoding(encode);
            sen.setContentType(contentType);
            httpPost.setEntity(sen);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                try {
                    HttpEntity resEntity = response.getEntity();
                    if (resEntity != null) {
                        result = EntityUtils.toString(resEntity, encode);
                    }
                } catch (Exception e) {
                    LOG.error("http pos throw Exception", e);
                }
            }
        } catch (ConnectionPoolTimeoutException e) {
            LOG.error("http pos throw ConnectionPoolTimeoutException(wait time out)", e.getMessage());
        } catch (ConnectTimeoutException e) {
            LOG.error("http pos throw ConnectTimeoutException", e.getMessage());
        } catch (SocketTimeoutException e) {
            LOG.error("http pos throw SocketTimeoutException", e.getMessage());
        } catch (ClientProtocolException e) {
            LOG.error("http pos throw ClientProtocolException", e.getMessage());
        } catch (IOException e) {
            LOG.error("http pos throw IOException", e.getMessage());
        } catch (Exception e) {
            LOG.error("http pos throw Exception", e.getMessage());
        } finally {
            if (null != httpClient) {
                httpClient.getConnectionManager().shutdown();
            }
        }
        return result;
    }

}

方式二:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.invoke.MethodHandles;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class TestInfrom{

    public static void main(String[] args) throws Exception {
        String url= "https://xxx:xxx";
        TestReqBean testReqBean = new TestReqBean();//传参bean
        String json= GsonUtil.getInstance().toJson(testReqBean);
        JSONObject res= postHttps(url, JSON.parseObject(json));
        System.out.println("inform_begin>>requestPath:" + requestPath+",res="+res);

    }
    public static JSONObject postHttps(String url, JSONObject parameters) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = parameters.keySet();
        for (String key : keySet) {
            String value = parameters.get(key).toString();
            if (value.equals("null") != true) {
                nameValuePairs.add(new BasicNameValuePair(key, value));
            }
        }
        return executeSendRequest(httpClient,httpPost,nameValuePairs);
    }

    private static JSONObject executeSendRequest(CloseableHttpClient httpclient, HttpPost httpPost, List<NameValuePair> nameValuePairs) throws Exception {
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
            httpPost.setEntity(uefEntity);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                return covertEntityToJSON(response.getEntity());
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    private static JSONObject covertEntityToJSON(HttpEntity entity) throws Exception {
        if (entity != null) {
            String res = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(res);
            return jsonObject;
        } else {
            return null;
        }
    }
}

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用httpclient发送https请求的步骤如下: 1. 创建HttpClient对象 首先,需要创建一个HttpClient对象。可以使用DefaultHttpClient类或HttpClientBuilder类来创建。 2. 创建HttpsURLConnection对象 使用URL对象的openConnection()方法创建HttpsURLConnection对象。 3. 设置SSLContext和TrustManager 为了支持https请求,需要设置SSLContext和TrustManager。SSLContext可以使用SSLContext.getInstance("TLS")来获取,TrustManager可以使用X509TrustManager实现。 4. 设置HostnameVerifier 设置HostnameVerifier,验证请求的主机名是否和证书中的主机名一致。可以使用DefaultHostnameVerifier类或自定义的HostnameVerifier类。 5. 设置请求头 可以使用setRequestProperty()方法设置请求头,比如User-Agent、Accept、Content-Type等。 6. 发送请求并获取响应 使用HttpURLConnection的getInputStream()方法获取响应的输入流,并使用IO流的方式读取响应数据。 示例代码如下: ```java // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpGet对象 HttpGet httpGet = new HttpGet("https://www.example.com"); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); // 读取响应数据 String result = EntityUtils.toString(entity, "UTF-8"); // 关闭响应和HttpClient对象 response.close(); httpClient.close(); ``` 需要注意的是,为了保证安全性,https请求中的证书需要进行验证。可以使用TrustManager来验证服务器证书的合法性,也可以使用自定义的SSLSocketFactory来忽略证书验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值