HttpClient的使用

  新引入Hutool-HttpUtil的使用(更简单,更强大!),详见http://www.cnblogs.com/jiangbei/p/7667858.html

一、概述

  1.简介

    根据凡技术必登其官网的原则(如果有),我们可以先访问其官网:http://hc.apache.org/httpcomponents-client-4.5.x/index.html

    摘取的简介如下:

    谷歌翻译如下:

  关于更加详细的本地化的介绍,可以参见网友的博客http://blog.csdn.net/wangpeng047/article/details/19624529/

  简单的来说,可以在Java代码中使用httpClient来调用服务(HTTP协议),类似之前在Ajax中发送请求类似

  2.相关教程

    可以参考官网给出的教程:http://hc.apache.org/httpcomponents-client-4.5.x/tutorial/html/index.html

二、入门

   1.下载

    这里采用的是maven进行构建,引入的依赖如下:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.3</version>
</dependency>

 

    当然,如果使用其它获取方式(jar或者gradle等),可以参见官网相关介绍:

      http://hc.apache.org/httpcomponents-client-4.5.x/httpclient/dependency-info.html

   2.起步

    这里参考上文随笔处的步骤与写法,当然,对于官网有quick start的,还是有必要进行阅读的:

      http://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html

    

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

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

    1.发送无参GET请求

 public static void main(String[] args) {
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建httpGet(请使用http://)
            HttpGet httpGet = new HttpGet("http://www.sogou.com");
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
           try {
               // 处理响应
               HttpEntity entity = response.getEntity();
               // 响应状态码
               System.out.println("=================================");
               System.out.println(response.getStatusLine().getStatusCode());
               // 打印响应体(使用工具类)
               System.out.println(EntityUtils.toString(entity));
               System.out.println("=================================");
           } finally { // 关闭response
               response.close();
           }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { // 关闭httpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

  结果:

  // 如果网页内容乱码,可以在toStrng位置加上编码参数

    2.发送带参数的GET请求(通过HttpGet的URI参数的构造器)

 public static void main(String[] args) {
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            // 创建URIBuilder
            URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com");
            // 设置参数
            uriBuilder.addParameter("query", "more love");
            // 使用URIBuilder创建httpGet
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpGet);
           try {
               // 处理响应
               HttpEntity entity = response.getEntity();
               // 响应状态码
               System.out.println("=================================");
               System.out.println(response.getStatusLine().getStatusCode());
               // 打印响应体(使用工具类)
               // System.out.println(EntityUtils.toString(entity));
               System.out.println("=================================");
           } finally { // 关闭response
               response.close();
           }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { // 关闭httpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

  // 核心就是URIBuilder对URI的创建,响应处理不变

    3.发送POST请求

public static void main(String[] args) {
        // 创建httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost("http://post_uri");
            List<NameValuePair> nvps = new ArrayList<>();
            nvps.add(new BasicNameValuePair("username", "vip"));
            nvps.add(new BasicNameValuePair("password", "secret"));
            // 同样可以指定参数的编码
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
           try {
               // 处理响应
               HttpEntity entity = response.getEntity();
               // 响应状态码
               System.out.println("=================================");
               System.out.println(response.getStatusLine().getStatusCode());
               // 打印响应体(使用工具类)
               // System.out.println(EntityUtils.toString(entity));
               System.out.println("=================================");
           } finally { // 关闭response
               response.close();
           }
        } catch (Exception e) {
            e.printStackTrace();
        } finally { // 关闭httpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

posted @ 2017-10-10 10:59  ---江北  阅读(510)  评论(0编辑  收藏  举报
TOP