Apache HttpClient4使用教程

基于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为例(推荐)
      //此处直接粘贴浏览器cookie
      final 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://www.jianshu.com/p/e6980bb463e9
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 每人身上都会有些与众不同之处,我也不例外,我身上的特点如同一条条可爱的虫虫,时常会发起争吵呢! ...
    花漾萦心阅读 295评论 0 2
  • 清明放假3天,因为最近公司事情很多,很少照顾到孩子学校的事情,导致最近老师要求家长给孩子做两个活动PPT,我一直没...
    rieichin阅读 167评论 2 0
  • 1. 函数声明和函数表达式有什么区别 函数声明: 声明不必放到调用的前面 函数表达式: 声明必需放到调用的前...
    peaceChierdo阅读 214评论 0 0