基于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.cnblogs.com/w-y-c-m/p/9237335.html

您的支持是对博主最大的鼓励,感谢您的认真阅读。

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

Apache HttpClient4使用教程的更多相关文章

  1. CentOS6.0(64位)安装Apache+PHP+Mysql教程,安装Magento(解决DOM,Mcrypt,GD问题)完整教程

    CentOS6.0(64位)安装Apache+PHP+Mysql教程,安装Magento(解决DOM,Mcrypt,GD问题)完整教程 0   Posted by :小黑 On : 2012 年 9 ...

  2. Tips & Tricks:Apache log4j简明教程(二)

    在上一讲Apache log4j简明教程(一)中介绍了log4j的基本概念,配置文件,以及将日志写入文件的方法,并给出了一个详细的示例.这一讲,我在继续谈一谈如何使用log4j将日志写入MySQL数据 ...

  3. Tips & Tricks:Apache log4j简明教程(一)

    Apache log4j的官方介绍是“log4j is a reliable, fast and flexible logging framework (APIs) written in Java, ...

  4. Apache Solr入门教程(初学者之旅)

    Apache Solr入门教程(初学者之旅) 写在前面:本文涉及solr入门的各方面,建议边思考边实践,相信能帮助你对solr有个清晰全面的了解并能简单实用. 在Apache Solr初学者教程的这个 ...

  5. Apache Solr 初级教程(介绍、安装部署、Java接口、中文分词)

    Python爬虫视频教程零基础小白到scrapy爬虫高手-轻松入门 https://item.taobao.com/item.htm?spm=a1z38n.10677092.0.0.482434a6E ...

  6. Apache Pig中文教程集合

    Apache Pig中文教程集合: http://www.codelast.com/?p=4550#more-4550

  7. 整合Apache与PHP教程

    Apache下载安装完成后,PHP下载解压后,最重要的是如何将他们连接起来,就是整合到一起,让它们之间有联系,笔者根据自己多次配的经验和帮学弟学妹配时他们的理解程度整理了一个比较详细易理解的版本,下面 ...

  8. 【翻译】Apache Shiro10分钟教程

    本文为翻译文,原文地址:http://shiro.apache.org/10-minute-tutorial.html 介绍 欢迎来到Apache Shiro的10分钟教程! 通过这个教程,你会明白一 ...

  9. Apache隐藏版本号教程(CentOS)

    1 找到Apache配置文件/etc/httpd/conf/httpd.conf 2 给该文件添加写权限:chmod u+w httpd.conf 3 打开该文件找到ServerTokens字段将其值 ...

随机推荐

  1. cocos2dx游戏--欢欢英雄传说--添加动作

    添加完人物之后接着给人物添加上动作.我们为hero添加4个动作:attack(由3张图片构成),walk(由2张图片构成),hit(由1张图片构成),dead(由1张图片构成):同样,为enemy添加 ...

  2. JSP自定义标签rtexprvalue属性

    rtexprvalue的全称是 Run-time Expression Value, 它用于表示是否可以使用JSP表达式.(比如EL表达式或OGNL表达式). 当在<attribute>标 ...

  3. JS时间格式化函数

    Date.prototype.format = function (format) { var o = { "M+": this.getMonth() + 1, //month & ...

  4. poj_2441 状态压缩dp

    题目大意 N头牛,M个谷仓,每个牛c都有它喜欢的若干个谷仓,现在要将这N头牛安排进谷仓,使得每个牛都位于它喜欢的谷仓,而每个谷仓只能有一头牛.求安排的方案总数.N, M <= 20 题目分析 将 ...

  5. c++11实现optional

    optional< T> c++14中将包含一个std::optional类,optional< T>内部存储空间可能存储了T类型的值也可能没有存储T类型的值.当optiona ...

  6. Docker源码分析(二):Docker Client创建与命令执行

    1. 前言 如今,Docker作为业界领先的轻量级虚拟化容器管理引擎,给全球开发者提供了一种新颖.便捷的软件集成测试与部署之道.在团队开发软件时,Docker可以提供可复用的运行环境.灵活的资源配置. ...

  7. 关于Memcached反射型DRDoS攻击分析

    一.Memcached反射攻击原理 1.反射DRDoS攻击: DRDoS攻击时DoS攻击的一种,DoS是指通过发送或引发大量的资源消耗导致服务不可用的一种攻击方式,中文称之为拒绝服务攻击.DRDoS是 ...

  8. Linux 搭建Nginx并添加配置 SSL 证书

    1. 安装准备   1.1 gcc安装 安装 nginx 需要先将官网下载的源码进行编译,编译依赖 gcc 环境,如果没有 gcc 环境,则需要安装: [root@nginx ~]# yum -y i ...

  9. spring cloud多个消费端重复定义feign client问题

    spring cloud消费端调用服务提供者,有两种方式rest+ribbon和Feign,Feign是一个声明式的伪Http客户端更为简单易用,所以我们项目选用Feign作为服务通讯方式 项目有6个 ...

  10. centos7 iptables/firewalld docker open port

    here are multiple "hackish" ways to do it: scan kernel logs, as mentioned by Jiri (but you ...