Apache HttpClient4使用教程

Apache HttpClient4使用教程基于HttpClient4.5.2执行GET请求CloseableHttpClienthttpClient=HttpClients.custom().build();CloseableHttpResponseresponse=httpClient.execute(newHttpGet("https://www.baidu.com"));…

大家好,又见面了,我是你们的朋友全栈君。

基于HttpClient 4.5.2

  1. 执行GET请求

    CloseableHttpClient httpClient = HttpClients.custom()
                    .build();
    CloseableHttpResponse response = httpClient.execute(new HttpGet("https://www.baidu.com"));
    System.out.println(EntityUtils.toString(response.getEntity()));
    
  2. 执行POST请求

    1. 提交form表单参数
      CloseableHttpClient httpClient = HttpClients.custom()
              .build();
      HttpPost httpPost = new HttpPost("https://www.explame.com");
      List<NameValuePair> formParams = new ArrayList<NameValuePair>();
      //表单参数
      formParams.add(new BasicNameValuePair("name1", "value1"));
      formParams.add(new BasicNameValuePair("name2", "value2"));
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, "utf-8");
      httpPost.setEntity(entity);
      CloseableHttpResponse response = httpClient.execute(httpPost);
      System.out.println(EntityUtils.toString(response.getEntity()));
      
    2. 提交payload参数
      CloseableHttpClient httpClient = HttpClients.custom()
                  .build();
      HttpPost httpPost = new HttpPost("https://www.explame.com");
      StringEntity entity = new StringEntity("{\"id\": \"1\"}");
      httpPost.setEntity(entity);
      CloseableHttpResponse response = httpClient.execute(httpPost);
      System.out.println(EntityUtils.toString(response.getEntity()));
      
    3. post上传文件
      CloseableHttpClient httpClient = HttpClients.custom()
              .build();
      HttpPost httpPost = new HttpPost("https://www.example.com");
      MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
      //要上传的文件
      multipartEntityBuilder.addBinaryBody("file", new File("temp.txt"));
      httpPost.setEntity(multipartEntityBuilder.build());
      CloseableHttpResponse response = httpClient.execute(httpPost);
      System.out.println(EntityUtils.toString(response.getEntity()));
      
    4. post提交multipart/form-data类型参数
      CloseableHttpClient httpClient = HttpClients.custom()
              .build();
      HttpPost httpPost = new HttpPost("https://www.example.com");
      MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
      multipartEntityBuilder.addTextBody("username","wycm");
      multipartEntityBuilder.addTextBody("passowrd","123");
      //文件
      multipartEntityBuilder.addBinaryBody("file", new File("temp.txt"));
      httpPost.setEntity(multipartEntityBuilder.build());
      CloseableHttpResponse response = httpClient.execute(httpPost);
      System.out.println(EntityUtils.toString(response.getEntity()));
      
  3. 设置User-Agent

        CloseableHttpClient httpClient = HttpClients.custom()
                .setUserAgent("Mozilla/5.0")
                .build();
        CloseableHttpResponse response = httpClient.execute(new HttpGet("https://www.baidu.com"));
        System.out.println(EntityUtils.toString(response.getEntity()));
    
  4. 设置重试处理器
    当请求超时, 会自动重试,最多3次

    HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {
        if (executionCount >= 3) {
            return false;
        }
        if (exception instanceof InterruptedIOException) {
            return true;
        }
        if (exception instanceof UnknownHostException) {
            return true;
        }
        if (exception instanceof ConnectTimeoutException) {
            return true;
        }
        if (exception instanceof SSLException) {
            return true;
        }
        HttpClientContext clientContext = HttpClientContext.adapt(context);
        HttpRequest request = clientContext.getRequest();
        boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
        if (idempotent) {
            return true;
        }
        return false;
    };
    CloseableHttpClient httpClient = HttpClients.custom()
            .setRetryHandler(retryHandler)
            .build();
    httpClient.execute(new HttpGet("https://www.baidu.com"));
    
  5. 重定向策略

    1. HttpClient默认情况
      会对302、307的GET和HEAD请求以及所有的303状态码做重定向处理
    2. 关闭自动重定向
      CloseableHttpClient httpClient = HttpClients.custom()
               //关闭httpclient重定向
              .disableRedirectHandling()
              .build();
      
    3. POST支持302状态码重定向
      CloseableHttpClient httpClient = HttpClients.custom()
          //post 302支持重定向
          .setRedirectStrategy(new LaxRedirectStrategy())
          .build();
      CloseableHttpResponse response = httpClient.execute(new HttpPost("https://www.explame.com"));
      System.out.println(EntityUtils.toString(response.getEntity()));
      
  6. 定制cookie

    • 方式一:通过addHeader方式设置(不推荐这种方式)
          CloseableHttpClient httpClient = HttpClients.custom()
                  .build();
          HttpGet httpGet = new HttpGet("http://www.example.com");
          httpGet.addHeader("Cookie", "name=value");
          httpClient.execute(httpGet);
      

      由于HttpClient默认会维护cookie状态。如果这个请求response中有Set-Cookie头,那下次请求的时候httpclient默认会把这个Cookie带上。并且会新建一行header。如果再遇到
      httpGet.addHeader("Cookie", "name=value");
      那么下次请求则会有两行name为Cookie的header。

    • 方式二:通过CookieStore的方式,以浏览器中的cookie为例(推荐)
      //此处直接粘贴浏览器cookiefinal String RAW_COOKIES = "name1=value1; name2=value2";final CookieStore cookieStore = new BasicCookieStore();for (String rawCookie : RAW_COOKIES.split("; ")){    String[] s = rawCookie.split("=");    BasicClientCookie cookie = new BasicClientCookie(s[0], s[1]);    cookie.setDomain("baidu.com");    cookie.setPath("/");    cookie.setSecure(false);    cookie.setAttribute("domain", "baidu.com");    Calendar calendar = Calendar.getInstance();    calendar.add(Calendar.DAY_OF_MONTH, +5);    cookie.setExpiryDate(calendar.getTime());    cookieStore.addCookie(cookie);}CloseableHttpClient httpClient = HttpClients.custom()        .setDefaultCookieStore(cookieStore)        .build();httpClient.execute(new HttpGet("https://www.baidu.com"));

      这种方式把定制的cookie交给httpclient维护。

  7. cookie管理

    • 方式一:初始化HttpClient时,传入一个自己CookieStore对象
      CookieStore cookieStore = new BasicCookieStore();
      CloseableHttpClient httpClient = HttpClients.custom()
              .setDefaultCookieStore(cookieStore)
              .build();
      httpClient.execute(new HttpGet("https://www.baidu.com"));
      //请求一次后,清理cookie再发起一次新的请求
      cookieStore.clear();
      httpClient.execute(new HttpGet("https://www.baidu.com"));
      
    • 方式二:每次执行请求的时候传入自己的HttpContext对象
      //注:HttpClientContext不是线程安全的,不要多个线程维护一个HttpClientContext
      HttpClientContext httpContext = HttpClientContext.create();
      CloseableHttpClient httpClient = HttpClients.custom()
              .build();
      httpClient.execute(new HttpGet("https://www.baidu.com"), httpContext);
      //请求一次后,清理cookie再发起一次新的请求
      httpContext.getCookieStore().clear();
      httpClient.execute(new HttpGet("https://www.baidu.com"));
      
  8. http代理的配置

    CloseableHttpClient httpClient = HttpClients.custom()
            //设置代理
            .setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost("localhost", 8888)))
            .build();
    CloseableHttpResponse response = httpClient.execute(new HttpGet("http://www.example.com"));
    System.out.println(EntityUtils.toString(response.getEntity()));
    
  9. SSL配置

    //默认信任
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType())
                    , (chain, authType) -> true).build();
    Registry<ConnectionSocketFactory> socketFactoryRegistry =
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", new SocketProxyPlainConnectionSocketFactory())
                    .register("https", new SocketProxySSLConnectionSocketFactory(sslContext))
                    .build();
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
            .build();
    HttpClientContext httpClientContext = HttpClientContext.create();
    httpClientContext.setAttribute("socks.address", new InetSocketAddress("127.0.0.1", 1086));
    CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/ip"), httpClientContext);
    System.out.println(EntityUtils.toString(response.getEntity()));
    
  10. socket代理配置

    static class SocketProxyPlainConnectionSocketFactory extends PlainConnectionSocketFactory{
        @Override
        public Socket createSocket(final HttpContext context) {
            InetSocketAddress socksAddr = (InetSocketAddress) context.getAttribute("socks.address");
            if (socksAddr != null){
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksAddr);
                return new Socket(proxy);
            } else {
                return new Socket();
            }
        }
    }
    static class SocketProxySSLConnectionSocketFactory extends SSLConnectionSocketFactory {
        public SocketProxySSLConnectionSocketFactory(final SSLContext sslContext) {
            super(sslContext, NoopHostnameVerifier.INSTANCE);
        }
    
        @Override
        public Socket createSocket(final HttpContext context) {
            InetSocketAddress socksAddr = (InetSocketAddress) context.getAttribute("socks.address");
            if (socksAddr != null){
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksAddr);
                return new Socket(proxy);
            } else {
                return new Socket();
            }
        }
    
    }
    /**
     * socket代理配置
     */
    public static void socketProxy() throws Exception {
        //默认信任
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType())
                        , (X509Certificate[] chain, String authType) -> true).build();
        Registry<ConnectionSocketFactory> socketFactoryRegistry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", new SocketProxyPlainConnectionSocketFactory())
                        .register("https", new SocketProxySSLConnectionSocketFactory(sslContext))
                        .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry))
                .build();
        HttpClientContext httpClientContext = HttpClientContext.create();
        httpClientContext.setAttribute("socks.address", new InetSocketAddress("127.0.0.1", 1086));
        CloseableHttpResponse response = httpClient.execute(new HttpGet("https://httpbin.org/ip"), httpClientContext);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
    
  11. 下载文件

    CloseableHttpClient httpClient = HttpClients.custom().build();
    CloseableHttpResponse response = httpClient.execute(new HttpGet("https://www.example.com"));
    InputStream is = response.getEntity().getContent();
    Files.copy(is, new File("temp.png").toPath(), StandardCopyOption.REPLACE_EXISTING);
    
    

最后

版权声明
作者:wycm
出处:https://blog.csdn.net/vwycm/article/details/88638996
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
一个程序员日常分享,包括但不限于爬虫、Java后端技术,欢迎关注

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/163238.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 密码学与网络安全第七版部分课后习题答案[通俗易懂]

    密码学与网络安全第七版部分课后习题答案[通俗易懂]第0章序言1.课后题汇总(仅部分)第一章思考题:1、2、4、5第二章习题:10、12、16第三章习题:9第四章思考题:4、5、6第五章习题:11第六章习题:2、6第七章思考题:2、3、4习题:4、7、8第八章习题:2第九章思考题:5、6习题:2、3第十章习题:1、2第十一章思考题:1、2、3第十二章思考题:1、3、4、7第十三章思考题:…

    2022年5月21日
    38
  • php中使用head进行二进制流输出,让用户下载PDF等附件的方法

    php中使用head进行二进制流输出,让用户下载PDF等附件的方法

    2021年9月20日
    41
  • 中间人攻击(MITM)姿势总结[通俗易懂]

    中间人攻击(MITM)姿势总结[通俗易懂]相关学习资料 http://www.cnblogs.com/LittleHann/p/3733469.htmlhttp://www.cnblogs.com/LittleHann/p/3738141.htmlhttp://www.cnblogs.com/LittleHann/p/3741907.htmlhttp://www.cnblogs.com/LittleHann/p/37082…

    2025年7月10日
    3
  • python3中eval函数用法简介[通俗易懂]

    python3中eval函数用法简介[通俗易懂]python中eval函数的用法十分的灵活,这里主要介绍一下它的原理和一些使用的场合。下面是从python的官方文档中的解释:  Theargumentsareastringandoptionalglobalsandlocals.Ifprovided,globalsmustbeadictionary.Ifprovided,localscan

    2025年8月11日
    3
  • VS 2017 产品密钥

    VS 2017 产品密钥个人分类 nbsp vs2010Visual VS2017 企业版 Enterprise 注册码 NJVYC BMHX2 G77MM 4XJMR 6Q8QFVisualS VS2017 专业版 Professional 激活码 key KBJFW NXHK6 W4WJM CRMQB G3CDH 启动 VS 之后 在菜单栏有个帮助的下拉框 选择注册产品

    2025年7月16日
    2
  • linux新增硬盘挂载_磁盘挂载什么意思

    linux新增硬盘挂载_磁盘挂载什么意思1、fdisk-l查看磁盘,并找到要挂载的磁盘(假设为/dev/vdb)2、fdisk/dev/vdb:•m显示命令列表•p显示磁盘分区同fdisk–l•n新增分区•d删除分区•w写入并退出3、顺序:n-输入分区编号-输入分区大小-p(查看分区)-w(保存分区)4、lsblk-l查看分区5、初始化磁盘:mkfs-text4/dev/vdb+分区编号6、lsblk-l查看分区UUID7、mount/dev/vdb+分区编号目

    2022年9月14日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号