Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 346|回复: 0

[默认分类] Apache HttpClient 实现 Java 调用 Http 接口

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-6-30 10:06:06 | 显示全部楼层 |阅读模式

    本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。


    1 新建一个测试用 Http URL,对登录的用户名和密码进行验证,并返回验证结果
    1.1 web.xml
    1. [code]<?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns="http://java.sun.com/xml/ns/javaee"
    4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    5. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    6. id="WebApp_ID"
    7. version="3.0">
    8.   <welcome-file-list>
    9.     <welcome-file>index.jsp</welcome-file>
    10.   </welcome-file-list>
    11.   <servlet>
    12.     <servlet-name>loginService</servlet-name>
    13.     <servlet-class>service.LoginService</servlet-class>
    14.     <load-on-startup>1</load-on-startup>
    15.   </servlet>
    16.   <servlet-mapping>
    17.     <servlet-name>loginService</servlet-name>
    18.     <url-pattern>/login</url-pattern>
    19.   </servlet-mapping>
    20. </web-app>
    复制代码
    [/code]
    1.2 Servlet
    1. [code]package service;
    2. import java.io.IOException;
    3. import java.io.OutputStream;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. public class LoginService extends HttpServlet {
    9.     @Override
    10.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    11.         throws ServletException, IOException {
    12.         String username = request.getParameter("username");
    13.         String password = request.getParameter("password");
    14.         OutputStream outputStream = response.getOutputStream();
    15.         response.setHeader("content-type", "application/json;charset=UTF-8");
    16.         String result = null;
    17.         if (username == null) {
    18.             result = "请输入用户名!";
    19.         } else if (password == null) {
    20.             result = "请输入密码!";
    21.         } else if (!username.equals("unique")) {
    22.             result = "用户名错误!";
    23.         } else if (!password.equals("ASDF")) {
    24.             result = "密码错误!";
    25.         } else {
    26.             result = "验证通过~~";
    27.         }
    28.         outputStream.write(result.getBytes("UTF-8"));
    29.     }
    30. }
    复制代码
    [/code]
    1.3 在浏览器中测试一下:





    2 通过 java 代码调用
    2.1 添加 Apache HttpClient 依赖包
    本文使用 Maven 管理依赖,关于 Maven 的使用可以参看:Apache Maven 或上网搜索相关资料
    注意:本文使用的 Apache HttpClient 版本是 4.5.3
    1. [code]<project xmlns="http://maven.apache.org/POM/4.0.0"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    4. http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5.   <modelVersion>4.0.0</modelVersion>
    6.   <groupId>jyl</groupId>
    7.   <artifactId>Service</artifactId>
    8.   <version>0.0.1-SNAPSHOT</version>
    9.   <packaging>war</packaging>
    10.   <dependencies>
    11.     <dependency>
    12.       <groupId>org.apache.httpcomponents</groupId>
    13.       <artifactId>httpclient</artifactId>
    14.       <version>4.5.3</version>
    15.     </dependency>
    16.     <dependency>
    17.       <groupId>junit</groupId>
    18.       <artifactId>junit</artifactId>
    19.       <version>4.12</version>
    20.     </dependency>
    21.   </dependencies>
    22. </project>
    复制代码
    [/code]
    2.2 编写单元测试
    1. [code]import java.io.IOException;
    2. import org.apache.http.HttpEntity;
    3. import org.apache.http.client.ClientProtocolException;
    4. import org.apache.http.client.methods.CloseableHttpResponse;
    5. import org.apache.http.client.methods.HttpGet;
    6. import org.apache.http.impl.client.CloseableHttpClient;
    7. import org.apache.http.impl.client.HttpClients;
    8. import org.apache.http.util.EntityUtils;
    9. import org.junit.Test;
    10. public class TestHttpClient {
    11.     @Test
    12.     public void test() {
    13.         CloseableHttpClient httpClient = HttpClients.createDefault();
    14.         HttpGet httpGet = new HttpGet("http://localhost:8080/Service/login");
    15.         CloseableHttpResponse httpResponse = null;
    16.         try {
    17.             httpResponse = httpClient.execute(httpGet);
    18.             System.out.print("Protocol Version :: ");
    19.             System.out.println(httpResponse.getProtocolVersion());
    20.             System.out.println("--------------------------------------------------");
    21.             System.out.print("Status Code :: ");
    22.             System.out.println(httpResponse.getStatusLine().getStatusCode());
    23.             System.out.println("--------------------------------------------------");
    24.             System.out.print("Reason Phrase :: ");
    25.             System.out.println(httpResponse.getStatusLine().getReasonPhrase());
    26.             System.out.println("--------------------------------------------------");
    27.             System.out.print("Status Line :: ");
    28.             System.out.println(httpResponse.getStatusLine().toString());
    29.             System.out.println("--------------------------------------------------");
    30.             HttpEntity httpEntity = httpResponse.getEntity();
    31.             System.out.print("Content Length :: ");
    32.             System.out.println(httpEntity.getContentLength());
    33.             System.out.println("--------------------------------------------------");
    34.             System.out.print("Content Type :: ");
    35.             System.out.println(httpEntity.getContentType());
    36.             System.out.println("--------------------------------------------------");
    37.             System.out.print("Content :: ");
    38.             System.out.println(httpEntity.getContent());
    39.             System.out.println("--------------------------------------------------");
    40.             System.out.print("Content Text :: ");
    41.             System.out.println(EntityUtils.toString(httpEntity));
    42.         } catch (ClientProtocolException e) {
    43.             e.printStackTrace();
    44.         } catch (IOException e) {
    45.             e.printStackTrace();
    46.         } finally {
    47.             try {
    48.                 httpClient.close();
    49.                 httpResponse.close();
    50.             } catch (IOException e) {
    51.                 e.printStackTrace();
    52.             }
    53.         }
    54.     }
    55. }
    复制代码
    [/code]
    2.3 测试结果

    2.4 修改 HttpGet 参数测试返回的 Content Text
    1. [code]HttpGet httpGet = new HttpGet("http://localhost:8080/Service/login?username=unique");
    复制代码
    [/code]

    1. [code]HttpGet httpGet = new HttpGet("http://localhost:8080/Service/login?username=unique&password=ASDF");
    复制代码
    [/code]

    3 关于 org.apache.http.util.EntityUtils 的使用注意事项
    官方文档中建议严格控制使用 EntityUtils 读取 HttpEntity 的信息,除非请求的 HTTP 服务器是一个授信的服务器且返回的结果长度在一定范围内,下面是官方文档中的原文
    1. [code]However, the use of EntityUtils is strongly discouraged unless the response entities originate from a trusted HTTP server and are known to be of limited length.
    复制代码
    [/code]
    4 向 HttpGet 传递 URI 参数
    可以向 HttpGet 传递一个 java.net.URI 参数代替字符串参数
    1. [code]import java.io.IOException;
    2. import java.net.URI;
    3. import java.net.URISyntaxException;
    4. import org.apache.http.HttpEntity;
    5. import org.apache.http.client.methods.CloseableHttpResponse;
    6. import org.apache.http.client.methods.HttpGet;
    7. import org.apache.http.client.utils.URIBuilder;
    8. import org.apache.http.impl.client.CloseableHttpClient;
    9. import org.apache.http.impl.client.HttpClients;
    10. import org.apache.http.util.EntityUtils;
    11. import org.junit.Test;
    12. public class TestHttpClient {
    13.     @Test
    14.     public void test() {
    15.         CloseableHttpClient httpClient = HttpClients.createDefault();
    16.         HttpGet httpGet = null;
    17.         CloseableHttpResponse httpResponse = null;
    18.         try {
    19.             URI uri = new URIBuilder()
    20.                 .setScheme("http")
    21.                 .setHost("localhost")
    22.                 .setPort(8080)
    23.                 .setPath("/Service/login")
    24.                 .setParameter("username", "unique")
    25.                 .setParameter("password", "ASDF")
    26.                 .build();
    27.             httpGet = new HttpGet(uri);
    28.             httpResponse = httpClient.execute(httpGet);
    29.             HttpEntity httpEntity = httpResponse.getEntity();
    30.             System.out.println(EntityUtils.toString(httpEntity));
    31.         } catch (URISyntaxException | IOException e) {
    32.             e.printStackTrace();
    33.         } finally {
    34.             try {
    35.                 httpClient.close();
    36.                 httpResponse.close();
    37.             } catch (IOException e) {
    38.                 e.printStackTrace();
    39.             }
    40.         }
    41.     }
    42. }
    复制代码
    [/code]
    5 调用 Http Post 方法
    5.1 将 Servlet 的 doGet 方法修改为 doPost,逻辑不变
    1. [code]@Override
    2. protected void doPost(HttpServletRequest request, HttpServletResponse response)
    3.     throws ServletException, IOException {
    4.     String username = request.getParameter("username");
    5.     String password = request.getParameter("password");
    6.     OutputStream outputStream = response.getOutputStream();
    7.     response.setHeader("content-type", "application/json;charset=UTF-8");
    8.     String result = null;
    9.     if (username == null) {
    10.         result = "请输入用户名!";
    11.     } else if (password == null) {
    12.         result = "请输入密码!";
    13.     } else if (!username.equals("unique")) {
    14.         result = "用户名错误!";
    15.     } else if (!password.equals("ASDF")) {
    16.         result = "密码错误!";
    17.     } else {
    18.         result = "验证通过~~";
    19.     }
    20.     outputStream.write(result.getBytes("UTF-8"));
    21. }
    复制代码
    [/code]
    5.2 使用 org.apache.http.client.methods.HttpPost 替换 HttpGet
    1. [code]import java.io.IOException;
    2. import java.util.ArrayList;
    3. import java.util.List;
    4. import org.apache.http.Consts;
    5. import org.apache.http.HttpEntity;
    6. import org.apache.http.NameValuePair;
    7. import org.apache.http.client.entity.UrlEncodedFormEntity;
    8. import org.apache.http.client.methods.CloseableHttpResponse;
    9. import org.apache.http.client.methods.HttpPost;
    10. import org.apache.http.impl.client.CloseableHttpClient;
    11. import org.apache.http.impl.client.HttpClients;
    12. import org.apache.http.message.BasicNameValuePair;
    13. import org.apache.http.util.EntityUtils;
    14. import org.junit.Test;
    15. public class TestHttpClient {
    16.     @Test
    17.     public void test() {
    18.         List<NameValuePair> params = new ArrayList<>();
    19.         params.add(new BasicNameValuePair("username", "unique"));
    20.         params.add(new BasicNameValuePair("password", "ASDF"));
    21.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
    22.         HttpPost httpPost = new HttpPost("http://localhost:8080/Service/login");
    23.         httpPost.setEntity(entity);
    24.         CloseableHttpClient httpClient = HttpClients.createDefault();
    25.         CloseableHttpResponse httpResponse = null;
    26.         try {
    27.             httpResponse = httpClient.execute(httpPost);
    28.             HttpEntity httpEntity = httpResponse.getEntity();
    29.             System.out.println(EntityUtils.toString(httpEntity));
    30.         } catch (IOException e) {
    31.             e.printStackTrace();
    32.         } finally {
    33.             try {
    34.                 httpClient.close();
    35.                 httpResponse.close();
    36.             } catch (IOException e) {
    37.                 e.printStackTrace();
    38.             }
    39.         }
    40.     }
    41. }
    复制代码
    [/code]
    5.3 同样给以给 HttpPost 传递 java.net.URI 参数取代字符串参数
    1. [code]import java.io.IOException;
    2. import java.net.URI;
    3. import java.net.URISyntaxException;
    4. import java.util.ArrayList;
    5. import java.util.List;
    6. import org.apache.http.Consts;
    7. import org.apache.http.HttpEntity;
    8. import org.apache.http.NameValuePair;
    9. import org.apache.http.client.entity.UrlEncodedFormEntity;
    10. import org.apache.http.client.methods.CloseableHttpResponse;
    11. import org.apache.http.client.methods.HttpPost;
    12. import org.apache.http.client.utils.URIBuilder;
    13. import org.apache.http.impl.client.CloseableHttpClient;
    14. import org.apache.http.impl.client.HttpClients;
    15. import org.apache.http.message.BasicNameValuePair;
    16. import org.apache.http.util.EntityUtils;
    17. import org.junit.Test;
    18. public class TestHttpClient {
    19.     @Test
    20.     public void test() {
    21.         List<NameValuePair> params = new ArrayList<>();
    22.         params.add(new BasicNameValuePair("username", "unique"));
    23.         params.add(new BasicNameValuePair("password", "ASDF"));
    24.         UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
    25.         CloseableHttpClient httpClient = HttpClients.createDefault();
    26.         CloseableHttpResponse httpResponse = null;
    27.         try {
    28.             URI uri = new URIBuilder()
    29.                 .setScheme("http")
    30.                 .setHost("localhost")
    31.                 .setPort(8080)
    32.                 .setPath("/Service/login")
    33.                 .build();
    34.             HttpPost httpPost = new HttpPost(uri);
    35.             httpPost.setEntity(entity);
    36.             httpResponse = httpClient.execute(httpPost);
    37.             HttpEntity httpEntity = httpResponse.getEntity();
    38.             System.out.println(EntityUtils.toString(httpEntity));
    39.         } catch (IOException e) {
    40.             e.printStackTrace();
    41.         } catch (URISyntaxException e) {
    42.             e.printStackTrace();
    43.         } finally {
    44.             try {
    45.                 httpClient.close();
    46.                 httpResponse.close();
    47.             } catch (IOException e) {
    48.                 e.printStackTrace();
    49.             }
    50.         }
    51.     }
    52. }
    复制代码
    [/code]
    6 提取调用接口的工具类
    1. [code]import java.io.IOException;
    2. import java.net.URI;
    3. import java.net.URISyntaxException;
    4. import java.util.ArrayList;
    5. import java.util.List;
    6. import java.util.Map;
    7. import org.apache.http.Consts;
    8. import org.apache.http.HttpEntity;
    9. import org.apache.http.NameValuePair;
    10. import org.apache.http.client.ClientProtocolException;
    11. import org.apache.http.client.entity.UrlEncodedFormEntity;
    12. import org.apache.http.client.methods.CloseableHttpResponse;
    13. import org.apache.http.client.methods.HttpGet;
    14. import org.apache.http.client.methods.HttpPost;
    15. import org.apache.http.client.utils.URIBuilder;
    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. public class HttpClientTool {
    21.     public class Method {
    22.         public static final String GET = "get";
    23.         public static final String POST = "post";
    24.     }
    25.     public static String invokeHttp(String method, String uri, Map<String, String> params)
    26.         throws IOException {
    27.         if (method.equals(HttpClientTool.Method.GET)) {
    28.             if (params == null) {
    29.                 return invokeHttpGet(uri);
    30.             } else {
    31.                 return invokeHttpGet(uri, params);
    32.             }
    33.         } else if (method.equals(HttpClientTool.Method.POST)) {
    34.             return invokeHttpPost(uri, params);
    35.         }
    36.         return null;
    37.     }
    38.     public static String invokeHttp(String method, URI uri, Map<String, String> params)
    39.         throws IOException, URISyntaxException {
    40.         if (method.equals(HttpClientTool.Method.GET)) {
    41.             if (params == null) {
    42.                 return invokeHttpGet(uri);
    43.             } else {
    44.                 return invokeHttpGet(uri, params);
    45.             }
    46.         } else if (method.equals(HttpClientTool.Method.POST)) {
    47.             return invokeHttpPost(uri, params);
    48.         }
    49.         return null;
    50.     }
    51.     public static String invokeHttp(String method, String scheme, String host, int port, String path, Map<String, String> params)
    52.         throws ClientProtocolException, URISyntaxException, IOException {
    53.         if (method.equals(HttpClientTool.Method.GET)) {
    54.             return invokeHttpGet(scheme, host, port, path, params);
    55.         } else if (method.equals(HttpClientTool.Method.POST)) {
    56.             return invokeHttpPost(scheme, host, port, path, params);
    57.         }
    58.         return null;
    59.     }
    60.     public static final String invokeHttpGet(String uri)
    61.         throws ClientProtocolException, IOException {
    62.         CloseableHttpClient client = HttpClients.createDefault();
    63.         CloseableHttpResponse response = null;
    64.         HttpGet httpGet = new HttpGet(uri);
    65.         try {
    66.             response = client.execute(httpGet);
    67.             HttpEntity entity = response.getEntity();
    68.             return EntityUtils.toString(entity);
    69.         } finally {
    70.             release(client, response);
    71.         }
    72.     }
    73.     public static final String invokeHttpGet(String uri, Map<String, String> params)
    74.         throws ClientProtocolException, IOException {
    75.         String executeUri = uri + "?";
    76.         for (Map.Entry<String, String> entry : params.entrySet()) {
    77.             executeUri += entry.getKey() + "=" + entry.getValue() + "&";
    78.         }
    79.         executeUri = executeUri.substring(0, executeUri.length() - 1);
    80.         CloseableHttpClient client = HttpClients.createDefault();
    81.         CloseableHttpResponse response = null;
    82.         HttpGet httpGet = new HttpGet(executeUri);
    83.         try {
    84.             response = client.execute(httpGet);
    85.             HttpEntity entity = response.getEntity();
    86.             return EntityUtils.toString(entity);
    87.         } finally {
    88.             release(client, response);
    89.         }
    90.     }
    91.     public static final String invokeHttpGet(URI uri)
    92.         throws ClientProtocolException, IOException {
    93.         CloseableHttpClient client = HttpClients.createDefault();
    94.         CloseableHttpResponse response = null;
    95.         HttpGet httpGet = new HttpGet(uri);
    96.         try {
    97.             response = client.execute(httpGet);
    98.             HttpEntity entity = response.getEntity();
    99.             return EntityUtils.toString(entity);
    100.         } finally {
    101.             release(client, response);
    102.         }
    103.     }
    104.     public static final String invokeHttpGet(URI uri, Map<String, String> params)
    105.         throws URISyntaxException, ClientProtocolException, IOException {
    106.         URIBuilder builder = new URIBuilder()
    107.             .setScheme(uri.getScheme())
    108.             .setHost(uri.getHost())
    109.             .setPort(uri.getPort())
    110.             .setPath(uri.getPath());
    111.         for (Map.Entry<String, String> entry : params.entrySet()) {
    112.             builder.setParameter(entry.getKey(), entry.getValue());
    113.         }
    114.         CloseableHttpClient client = HttpClients.createDefault();
    115.         CloseableHttpResponse response = null;
    116.         HttpGet httpGet = new HttpGet(builder.build());
    117.         try {
    118.             response = client.execute(httpGet);
    119.             HttpEntity entity = response.getEntity();
    120.             return EntityUtils.toString(entity);
    121.         } finally {
    122.             release(client, response);
    123.         }
    124.     }
    125.     public static final String invokeHttpGet(String scheme, String host, int port, String path, Map<String, String> params)
    126.         throws URISyntaxException, ClientProtocolException, IOException {
    127.         URIBuilder builder = new URIBuilder()
    128.             .setScheme(scheme)
    129.             .setHost(host)
    130.             .setPort(port)
    131.             .setPath(path);
    132.         for (Map.Entry<String, String> entry : params.entrySet()) {
    133.             builder.setParameter(entry.getKey(), entry.getValue());
    134.         }
    135.         URI uri = builder.build();
    136.         return invokeHttpGet(uri);
    137.     }
    138.     public static final String invokeHttpPost(String uri, Map<String, String> params)
    139.         throws ClientProtocolException, IOException {
    140.         CloseableHttpClient client = HttpClients.createDefault();
    141.         CloseableHttpResponse response = null;
    142.         HttpPost httpPost = new HttpPost(uri);
    143.         httpPost.setEntity(generatePostEntity(params));
    144.         try {
    145.             response = client.execute(httpPost);
    146.             HttpEntity httpEntity = response.getEntity();
    147.             return EntityUtils.toString(httpEntity);
    148.         } finally {
    149.             release(client, response);
    150.         }
    151.     }
    152.     public static final String invokeHttpPost(URI uri, Map<String, String> params)
    153.         throws ClientProtocolException, IOException {
    154.         CloseableHttpClient client = HttpClients.createDefault();
    155.         CloseableHttpResponse response = null;
    156.         HttpPost httpPost = new HttpPost(uri);
    157.         httpPost.setEntity(generatePostEntity(params));
    158.         try {
    159.             response = client.execute(httpPost);
    160.             HttpEntity httpEntity = response.getEntity();
    161.             return EntityUtils.toString(httpEntity);
    162.         } finally {
    163.             release(client, response);
    164.         }
    165.     }
    166.     public static final String invokeHttpPost(String scheme, String host, int port, String path, Map<String, String> params)
    167.         throws URISyntaxException, ClientProtocolException, IOException {
    168.         URIBuilder builder = new URIBuilder()
    169.             .setScheme(scheme)
    170.             .setHost(host)
    171.             .setPort(port)
    172.             .setPath(path);
    173.         URI uri = builder.build();
    174.         return invokeHttpPost(uri, params);
    175.     }
    176.     private static UrlEncodedFormEntity generatePostEntity(Map<String, String> params) {
    177.         List<NameValuePair> pairs = new ArrayList<>();
    178.         for (Map.Entry<String, String> entry : params.entrySet()) {
    179.             pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    180.         }
    181.         return new UrlEncodedFormEntity(pairs, Consts.UTF_8);
    182.     }
    183.     private static void release(CloseableHttpClient client, CloseableHttpResponse response)
    184.         throws IOException {
    185.         if (client != null) {
    186.             client.close();
    187.         }
    188.         if (response != null) {
    189.             response.close();
    190.         }
    191.     }
    192. }
    复制代码
    [/code]

    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2025-2-24 07:23 , Processed in 0.383744 second(s), 36 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表