HttpClient浅入学习

本文介绍了如何使用Apache HttpClient 4.5.3进行HTTP请求的发送,包括创建默认及自定义配置的HttpClient实例的方法,通过示例展示了设置代理服务器及认证信息的过程,以及如何处理HTTPS请求并绕过证书验证。

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

基于:httpclient 4.5.3

1、httpclient的获得

1.1 httpclients

static CloseableHttpClient createDefault()

Creates CloseableHttpClient instance with default configuration.

static CloseableHttpClient createMinimal()

Creates CloseableHttpClient instance that implements the most basic HTTP protocol support.

static CloseableHttpClient createMinimal(HttpClientConnectionManager connManager)

Creates CloseableHttpClient instance that implements the most basic HTTP protocol support.

static CloseableHttpClient createSystem()

Creates CloseableHttpClient instance with default configuration based on ssytem properties.

static HttpClientBuilder custom()

Creates builder object for construction of custom CloseableHttpClient instances.--创建自定义的httpclient

1.2 httpclientUtils

static void closeQuietly(CloseableHttpResponse response)

Unconditionally close a response.

static void closeQuietly(HttpClient httpClient)

Unconditionally close a httpClient.

static void closeQuietly(org.apache.http.HttpResponse response)

Unconditionally close a response.

public static void closeQuietly(org.apache.http.HttpResponse response)

Unconditionally close a response.

Example Code:

HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (Exception e) {
// error handling
} finally {
HttpClientUtils.closeQuietly(httpResponse);
}

Parameters:

response - the HttpResponse to release resources, may be null or already closed. Since: 4.2

1、代理实现,参考官网的例子<需要用户认证>

public void previ1() throws ClientProtocolException, IOException
    {
//      HttpHost target = new HttpHost("httpbin.org", 8080, "https");
      AuthScope authscope = new AuthScope("proxyxx.xx.com", 8080,"http");
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      Credentials credentials = new UsernamePasswordCredentials("username", "password");  
      credentialsProvider.setCredentials(authscope, credentials); 

      CloseableHttpClient httpclient = HttpClients.custom()
                                                .setDefaultCredentialsProvider(credentialsProvider)
                                                .build();
      HttpGet request = new HttpGet("http:xxxx");
      System.out.println("Executing request " + request.getRequestLine()  + " via " + authscope.getHost());

      CloseableHttpResponse response = httpclient.execute(request);
      try
      {
          System.out.println("----------------------------------------");

          System.out.println(response.getStatusLine());

          System.out.println(EntityUtils.toString(response.getEntity()));

      } finally 
      {
          response.close();
          httpclient.close();
      }
    }

2、https验证<具体对https的只是了解还不多,不太懂啥意思>

private static SSLContextBuilder builder = null;
private static SSLConnectionSocketFactory sslsf = null;
private static PoolingHttpClientConnectionManager cm = null;
    static {
        try {
            builder = new SSLContextBuilder();
            // 全部信任 不做身份鉴定
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
 sslsf = new SSLConnectionSocketFactory(builder.build(), 
            new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new PlainConnectionSocketFactory())
                    .register("https", sslsf)
                    .build();

            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(200);//max connection
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3、-------------main方法中写入-------------<需要使用user+pass获取token>

CloseableHttpClient httpclient =HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setConnectionManager(cm)
                .setConnectionManagerShared(true)
                .build();

 HttpEntity entity = EntityBuilder.create()
                .setText("{\"userid\":\"admin\",\"pass\":\"password\"}")//转义"
                .setContentType(ContentType.DEFAULT_TEXT)
                .build();           //entity对象可以研究下

 HttpUriRequest request=RequestBuilder.put("https://10.120.xx.xx:port/itpaas/uam/auth/token")
                .setEntity(entity)
                .setHeader("Content-Type", "application/json; charset=UTF-8")
                .setHeader("language", "CH/EN")
                .build();
CloseableHttpResponse response = httpclient.execute(request);

System.out.println(response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值