• Java HttpClient库的使用


    (一)简介

    HttpClient是Apache的一个开源库,相比于JDK自带的URLConnection等,使用起来更灵活方便。

    使用方法可以大致分为如下八步曲:

    1、创建一个HttpClient对象;

    2、创建一个Http请求对象并设置请求的URL,比如GET请求就创建一个HttpGet对象,POST请求就创建一个HttpPost对象;

    3、如果需要可以设置请求对象的请求头参数,也可以往请求对象中添加请求参数;

    4、调用HttpClient对象的execute方法执行请求;

    5、获取请求响应对象和响应Entity;

    6、从响应对象中获取响应状态,从响应Entity中获取响应内容;

    7、关闭响应对象;

    8、关闭HttpClient.

    (二)在本地创建一个Servlet程序

    在本地创建一个Servlet程序并跑在Tomcat服务器中,主要用于下一步测试HttpClient发送请求。

    注:Servlet的创建方法详见:微信公众号开发【技术基础】(一):Eclipse+Tomcat搭建本地服务器并跑通HelloWorld程序

    1、Servlet类:

    复制代码
     1 import java.io.PrintWriter;
     2 
     3 import javax.servlet.http.HttpServlet;
     4 import javax.servlet.http.HttpServletRequest;
     5 import javax.servlet.http.HttpServletResponse;
     6 
     7 public class HelloWorld extends HttpServlet {
     8     private static final long serialVersionUID = 4601029764222607869L;
     9 
    10     @Override
    11     protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    12         // 1. 设置编码格式
    13         resp.setContentType("text/html");
    14         resp.setCharacterEncoding("UTF-8");
    15 
    16         // 2. 往返回体中写返回数据
    17         PrintWriter writer = null;
    18         try {
    19             writer = resp.getWriter();
    20             writer.print("Hello world! 你好,世界!!");
    21         } catch (Exception e) {
    22             e.printStackTrace();
    23         } finally {
    24             writer.close();
    25         }
    26     }
    27 
    28     @Override
    29     protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    30         // 1. 获取请求的参数
    31         String userName = req.getParameter("username");
    32         String password = req.getParameter("password");
    33 
    34         // 2. 往返回体写返回数据
    35         PrintWriter writer = null;
    36         try {
    37             writer = resp.getWriter();
    38             writer.print("your username is:" + userName + "
    your password is:" + password);
    39         } catch (Exception e) {
    40             e.printStackTrace();
    41         } finally {
    42             writer.close();
    43         }
    44     }
    45 
    46 }
    复制代码

    2、web.xml(新加内容):

    复制代码
    1   <servlet>
    2         <servlet-name>helloWorld</servlet-name>
    3         <servlet-class>com.servlet.HelloWorld</servlet-class>
    4     </servlet>
    5 
    6     <servlet-mapping>
    7         <servlet-name>helloWorld</servlet-name>
    8         <url-pattern>/hello</url-pattern>
    9     </servlet-mapping>
    复制代码

    (三)测试HttpClient发送GET和POST请求

    1、HttpClient测试类:

    复制代码
      1 package com.test.method;
      2 
      3 import java.io.IOException;
      4 import java.io.UnsupportedEncodingException;
      5 import java.util.ArrayList;
      6 import java.util.List;
      7 
      8 import org.apache.http.HttpEntity;
      9 import org.apache.http.NameValuePair;
     10 import org.apache.http.ParseException;
     11 import org.apache.http.client.ClientProtocolException;
     12 import org.apache.http.client.entity.UrlEncodedFormEntity;
     13 import org.apache.http.client.methods.CloseableHttpResponse;
     14 import org.apache.http.client.methods.HttpGet;
     15 import org.apache.http.client.methods.HttpPost;
     16 import org.apache.http.impl.client.CloseableHttpClient;
     17 import org.apache.http.impl.client.HttpClients;
     18 import org.apache.http.message.BasicNameValuePair;
     19 import org.apache.http.util.EntityUtils;
     20 
     21 /**
     22  * 测试HttpClient发送各种请求的方法
     23  * 
     24  * @author Administrator
     25  *
     26  */
     27 public class HttpClientTest {
     28     // 发送请求的url
     29     public static final String REQUEST_URL = "http://localhost:8080/TomcatTest/hello";
     30 
     31     /**
     32      * 测试发送GET请求
     33      */
     34     public void get() {
     35         // 1. 创建一个默认的client实例
     36         CloseableHttpClient client = HttpClients.createDefault();
     37 
     38         try {
     39             // 2. 创建一个httpget对象
     40             HttpGet httpGet = new HttpGet(REQUEST_URL);
     41             System.out.println("executing GET request " + httpGet.getURI());
     42 
     43             // 3. 执行GET请求并获取响应对象
     44             CloseableHttpResponse resp = client.execute(httpGet);
     45 
     46             try {
     47                 // 4. 获取响应体
     48                 HttpEntity entity = resp.getEntity();
     49                 System.out.println("------");
     50 
     51                 // 5. 打印响应状态
     52                 System.out.println(resp.getStatusLine());
     53 
     54                 // 6. 打印响应长度和响应内容
     55                 if (null != entity) {
     56                     System.out.println("Response content length = " + entity.getContentLength());
     57                     System.out.println("Response content is:
    " + EntityUtils.toString(entity));
     58                 }
     59 
     60                 System.out.println("------");
     61             } finally {
     62                 // 7. 无论请求成功与否都要关闭resp
     63                 resp.close();
     64             }
     65         } catch (ClientProtocolException e) {
     66             e.printStackTrace();
     67         } catch (ParseException e) {
     68             e.printStackTrace();
     69         } catch (IOException e) {
     70             e.printStackTrace();
     71         } finally {
     72             // 8. 最终要关闭连接,释放资源
     73             try {
     74                 client.close();
     75             } catch (Exception e) {
     76                 e.printStackTrace();
     77             }
     78         }
     79     }
     80 
     81     /**
     82      * 测试发送POST请求
     83      */
     84     public void post() {
     85         // 1. 获取默认的client实例
     86         CloseableHttpClient client = HttpClients.createDefault();
     87         // 2. 创建httppost实例
     88         HttpPost httpPost = new HttpPost(REQUEST_URL);
     89         // 3. 创建参数队列(键值对列表)
     90         List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
     91         paramPairs.add(new BasicNameValuePair("username", "admin"));
     92         paramPairs.add(new BasicNameValuePair("password", "123456"));
     93 
     94         UrlEncodedFormEntity entity;
     95 
     96         try {
     97             // 4. 将参数设置到entity对象中
     98             entity = new UrlEncodedFormEntity(paramPairs, "UTF-8");
     99 
    100             // 5. 将entity对象设置到httppost对象中
    101             httpPost.setEntity(entity);
    102 
    103             System.out.println("executing POST request " + httpPost.getURI());
    104 
    105             // 6. 发送请求并回去响应
    106             CloseableHttpResponse resp = client.execute(httpPost);
    107 
    108             try {
    109                 // 7. 获取响应entity
    110                 HttpEntity respEntity = resp.getEntity();
    111 
    112                 // 8. 打印出响应内容
    113                 if (null != respEntity) {
    114                     System.out.println("------");
    115                     System.out.println(resp.getStatusLine());
    116                     System.out.println("Response content is : 
    " + EntityUtils.toString(respEntity, "UTF-8"));
    117 
    118                     System.out.println("------");
    119                 }
    120             } finally {
    121                 // 9. 关闭响应对象
    122                 resp.close();
    123             }
    124 
    125         } catch (ClientProtocolException e) {
    126             e.printStackTrace();
    127         } catch (UnsupportedEncodingException e) {
    128             e.printStackTrace();
    129         } catch (IOException e) {
    130             e.printStackTrace();
    131         } finally {
    132             // 10. 关闭连接,释放资源
    133             try {
    134                 client.close();
    135             } catch (Exception e) {
    136                 e.printStackTrace();
    137             }
    138         }
    139     }
    140 
    141     public static void main(String[] args) {
    142         HttpClientTest test = new HttpClientTest();
    143         // 测试GET请求
    144         test.get();
    145         // 测试POST请求
    146         test.post();
    147     }
    148 }
    复制代码

    2、输出结果:

    executing GET request http://localhost:8080/TomcatTest/hello
    ------
    HTTP/1.1 200 OK
    Response content length = 34
    Response content is:
    Hello world! 你好,世界!!
    ------
    executing POST request http://localhost:8080/TomcatTest/hello
    ------
    HTTP/1.1 200 OK
    Response content is :
    your username is:admin
    your password is:123456
    ------

     (四)jar包下载

    所需jar包打包下载地址:https://pan.baidu.com/s/1mhJ9iT6

  • 相关阅读:
    Spreadsheet 使用介绍
    一套完整自定义工作流的实现(2)
    《WF编程》系列之 承载工作流:持久性服务 Persistence Services
    SQL Server 2005函数
    ActiveReport
    SQLServer 2000中,存储过程和用户自定义函数具体的区别??
    MS SQL Server 2005 物理查询处理中的各个阶段(二)
    《WF编程》系列 承载工作流:持久化与跟踪
    C# WinForm自定义控件整理
    SQL Server2005使用CTE实现递归
  • 原文地址:https://www.cnblogs.com/jpfss/p/7988675.html
Copyright © 2020-2023  润新知