HttpClient中post请求http、https

HttpClient中post请求http、https示例

HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

创建CloseableHttpClient对象。
创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
如果需要发送请求参数,可可调用setEntity(HttpEntity entity)方法来设置请求参数。setParams方法已过时(4.4.1版本)。
调用HttpGet、HttpPost对象的setHeader(String name, String value)方法设置header信息,或者调用setHeaders(Header[] headers)设置一组header信息。
调用CloseableHttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个CloseableHttpResponse。
调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容;调用CloseableHttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头。
释放连接。无论执行方法是否成功,都必须释放连接
具体代码如下(HttpClient-4.4.1):

/**

  • 简单httpclient实例
    */
    public class SimpleHttpClientDemo {

    /**

    • 模拟请求

    • @param url 资源地址

    • @param map 参数列表

    • @param encoding 编码

    • @return

    • @throws ParseException

    • @throws IOException
      */
      public static String send(String url, Map<String,String> map,String encoding) throws ParseException, IOException{
      String body = “”;

      //创建httpclient对象
      CloseableHttpClient client = HttpClients.createDefault();
      //创建post方式请求对象
      HttpPost httpPost = new HttpPost(url);

      //装填参数
      List nvps = new ArrayList();
      if(map!=null){
      for (Entry<String, String> entry : map.entrySet()) {
      nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
      }
      //设置参数到请求对象中
      httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

      System.out.println(“请求地址:”+url);
      System.out.println(“请求参数:”+nvps.toString());

      //设置header信息
      //指定报文头【Content-type】、【User-Agent】
      httpPost.setHeader(“Content-type”, “application/x-www-form-urlencoded”);
      httpPost.setHeader(“User-Agent”, “Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)”);

      //执行请求操作,并拿到结果(同步阻塞)
      CloseableHttpResponse response = client.execute(httpPost);
      //获取结果实体
      HttpEntity entity = response.getEntity();
      if (entity != null) {
      //按指定编码转换结果实体为String类型
      body = EntityUtils.toString(entity, encoding);
      }
      EntityUtils.consume(entity);
      //释放链接
      response.close();
      return body;
      }
      }

对于HTTPS的访问,采取绕过证书的策略:

/**
 * 绕过验证
 *     
 * @return
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 */
public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sc = SSLContext.getInstance("SSLv3");

    // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
    X509TrustManager trustManager = new X509TrustManager() {
        @Override
        public void checkClientTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    sc.init(null, new TrustManager[] { trustManager }, null);
    return sc;
}

然后修改原来的send方法:

/**
 * 模拟请求
 * 
 * @param url        资源地址
 * @param map    参数列表
 * @param encoding    编码
 * @return
 * @throws NoSuchAlgorithmException 
 * @throws KeyManagementException 
 * @throws IOException 
 * @throws ClientProtocolException 
 */
public static String send(String url, Map<String,String> map,String encoding) throws KeyManagementException, NoSuchAlgorithmException, ClientProtocolException, IOException {
    String body = "";
    //采用绕过验证的方式处理https请求
    SSLContext sslcontext = createIgnoreVerifySSL();
    
    // 设置协议http和https对应的处理socket链接工厂的对象
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", PlainConnectionSocketFactory.INSTANCE)
        .register("https", new SSLConnectionSocketFactory(sslcontext))
        .build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);

    //创建自定义的httpclient对象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();

// CloseableHttpClient client = HttpClients.createDefault();

    //创建post方式请求对象
    HttpPost httpPost = new HttpPost(url);
    
    //装填参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if(map!=null){
        for (Entry<String, String> entry : map.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    //设置参数到请求对象中
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

    System.out.println("请求地址:"+url);
    System.out.println("请求参数:"+nvps.toString());
    
    //设置header信息
    //指定报文头【Content-type】、【User-Agent】
    httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    
    //执行请求操作,并拿到结果(同步阻塞)
    CloseableHttpResponse response = client.execute(httpPost);
    //获取结果实体
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //按指定编码转换结果实体为String类型
        body = EntityUtils.toString(entity, encoding);
    }
    EntityUtils.consume(entity);
    //释放链接
    response.close();
    return body;
}

但是,如果是自己用jdk或者其他工具生成的证书,还是希望用其他方式认证自签名的证书,这篇文章就来分享一下如何设置信任自签名的证书。当然你也可以参考官网示例中。

要想信任自签名的证书,必须得知道密钥库的路径及密钥库的密码。然后加载到程序来才可以。具体代码如下:

/**
 * 设置信任自签名证书
 *     
 * @param keyStorePath        密钥库路径
 * @param keyStorepass        密钥库密码
 * @return
 */
public static SSLContext custom(String keyStorePath, String keyStorepass){
    SSLContext sc = null;
    FileInputStream instream = null;
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        instream = new FileInputStream(new File(keyStorePath));
        trustStore.load(instream, keyStorepass.toCharArray());
        // 相信自己的CA和所有自签名的证书
        sc = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
    } catch (KeyStoreException | NoSuchAlgorithmException| CertificateException | IOException | KeyManagementException e) {
        e.printStackTrace();
    } finally {
        try {
            instream.close();
        } catch (IOException e) {
        }
    }
    return sc;
}

然后修改原来的send方法:

/**
 * 模拟请求
 * 
 * @param url        资源地址
 * @param map    参数列表
 * @param encoding    编码
 * @return
 * @throws ParseException
 * @throws IOException
 * @throws KeyManagementException 
 * @throws NoSuchAlgorithmException 
 * @throws ClientProtocolException 
 */
public static String send(String url, Map<String,String> map,String encoding) throws ClientProtocolException, IOException {
    String body = "";
    
    //tomcat是我自己的密钥库的密码,你可以替换成自己的
    //如果密码为空,则用"nopassword"代替
    SSLContext sslcontext = custom("D:\\keys\\wsriakey", "tomcat");
    
    // 设置协议http和https对应的处理socket链接工厂的对象
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
        .register("http", PlainConnectionSocketFactory.INSTANCE)
        .register("https", new SSLConnectionSocketFactory(sslcontext))
        .build();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClients.custom().setConnectionManager(connManager);

    //创建自定义的httpclient对象
    CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();

// CloseableHttpClient client = HttpClients.createDefault();

    //创建post方式请求对象
    HttpPost httpPost = new HttpPost(url);
    
    //装填参数
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    if(map!=null){
        for (Entry<String, String> entry : map.entrySet()) {
            nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
    }
    //设置参数到请求对象中
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));

    System.out.println("请求地址:"+url);
    System.out.println("请求参数:"+nvps.toString());
    
    //设置header信息
    //指定报文头【Content-type】、【User-Agent】
    httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
    httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    
    //执行请求操作,并拿到结果(同步阻塞)
    CloseableHttpResponse response = client.execute(httpPost);
    //获取结果实体
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //按指定编码转换结果实体为String类型
        body = EntityUtils.toString(entity, encoding);
    }
    EntityUtils.consume(entity);
    //释放链接
    response.close();
    return body;
}
Java利用HttpClient进行POST请求(HTTPS)实例可以通过以下步骤完成: 1. 导入所需的类和包。您需要引入org.apache.http.client包下的HttpClientHttpPost类,以及org.apache.http.impl.client包下的CloseableHttpClient类。 2. 创建CloseableHttpClient对象。您可以使用HttpClientBuilder类的create()方法来创建一个CloseableHttpClient对象。 3. 创建HttpPost对象并设置URL。您需要创建HttpPost对象,并使用setURI()方法设置要发送请求的URL。 4. 设置请求参数。您可以使用NameValuePair来设置请求参数,然后通过setEntity()方法设置到HttpPost对象。 5. 执行POST请求并获取响应。使用CloseableHttpClient对象的execute()方法执行POST请求,将HttpPost对象作为参数传递给execute()方法。然后,获取HttpResponse对象并从提取响应内容。 下面是一个示例代码: ``` import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class HttpClientPostExample { public static void main(String[] args) { String url = "https://example.com/post"; // 设置要发送的URL try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpPost httpPost = new HttpPost(url); // 创建HttpPost对象并设置URL List<NameValuePair> params = new ArrayList<>(); // 创建请求参数列表 params.add(new BasicNameValuePair("key1", "value1")); // 设置请求参数 params.add(new BasicNameValuePair("key2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置请求参数到HttpPost对象 HttpResponse httpResponse = httpClient.execute(httpPost); // 执行POST请求并获取响应 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 判断响应状态码 String response = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8); System.out.println("响应内容:" + response); } else { System.out.println("POST请求失败!"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例展示了如何使用Apache HttpClient库进行POST请求,并向请求添加参数。其,我们使用了URL编码工具类URLEncodedUtils和EntityUtils来处理请求参数和响应内容。请根据实际情况修改URL和请求参数,并根据需要处理响应结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值