• HttpClient远程使用大全


    HttpClient简介

    1.1 概述

    HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。主要实现功能:

    实现了所有 HTTP 的方法(GET、POST、PUT、HEAD、DELETE、HEAD、OPTIONS 等)

    支持 HTTPS 协议

    支持代理服务器(Nginx等)等

    支持自动(跳转)转向。

    1.2 案例工程介绍

    1.2.1 工程截图

    请求端:16-spt-http-request-demo  :7000     响应端:16-spt-httppush-demo :8082

    1.2.2 引入依赖

    1. <!-- httpclient -->
    2. <dependency>
    3. <groupId>org.apache.httpcomponents</groupId>
    4. <artifactId>httpclient</artifactId>
    5. <version>4.5.5</version>
    6. </dependency>
    7. <!-- fastjson -->
    8. <dependency>
    9. <groupId>com.alibaba</groupId>
    10. <artifactId>fastjson</artifactId>
    11. <version>1.2.47</version>
    12. </dependency>

    注:SpringBoot的基本依赖配置,这里就不再多说了

    二  实操实例Get方式

    2.1 get无参数案例

    1.消费者

    1. @RestController
    2. public class HttpClientController {
    3. @RequestMapping("/hc/api")
    4. public String getInfo() throws Exception {
    5. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    6. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    7. // 创建Get请求
    8. HttpGet httpGet = new HttpGet("http://localhost:8082/get/noparam");
    9. String result="";
    10. // 响应模型
    11. CloseableHttpResponse response = null;
    12. try {
    13. // 由客户端执行(发送)Get请求
    14. response = httpClient.execute(httpGet);
    15. // 从响应模型中获取响应实体
    16. HttpEntity responseEntity = response.getEntity();
    17. System.out.println("响应状态为:" + response.getStatusLine());
    18. if (responseEntity != null) {
    19. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    20. result=EntityUtils.toString(responseEntity);
    21. System.out.println("响应内容为:" + result);
    22. }
    23. } catch (ClientProtocolException e) {
    24. e.printStackTrace();
    25. } catch (ParseException e) {
    26. e.printStackTrace();
    27. } catch (IOException e) {
    28. e.printStackTrace();
    29. } finally {
    30. try {
    31. // 释放资源
    32. if (httpClient != null) {
    33. httpClient.close();
    34. }
    35. if (response != null) {
    36. response.close();
    37. }
    38. } catch (IOException e) {
    39. e.printStackTrace();
    40. }
    41. }
    42. return result;
    43. }
    44. }

    2.服务者

    1. @RestController
    2. public class HttpClientController {
    3. @RequestMapping("/get/noparam")
    4. public String doGetNoParam(){
    5. return "ok 123!";
    6. }
    7. }

    截图如下: 

    3.请求测试

    2.2 get有参数:直接拼接URL

    1.消费者

    1. @RequestMapping("/hc/get/youcan")
    2. public String youcanOne() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 参数
    6. StringBuffer params = new StringBuffer();
    7. try {
    8. // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
    9. params.append("name=" + URLEncoder.encode("zhangsan", "utf-8"));
    10. params.append("&");
    11. params.append("age=24");
    12. } catch (UnsupportedEncodingException e1) {
    13. e1.printStackTrace();
    14. }
    15. // 创建Get请求
    16. HttpGet httpGet = new HttpGet("http://localhost:8082/get/youparam1" + "?" + params);
    17. // 响应模型
    18. CloseableHttpResponse response = null;
    19. String result="";
    20. try {
    21. // 配置信息
    22. RequestConfig requestConfig = RequestConfig.custom()
    23. // 设置连接超时时间(单位毫秒)
    24. .setConnectTimeout(5000)
    25. // 设置请求超时时间(单位毫秒)
    26. .setConnectionRequestTimeout(5000)
    27. // socket读写超时时间(单位毫秒)
    28. .setSocketTimeout(5000)
    29. // 设置是否允许重定向(默认为true)
    30. .setRedirectsEnabled(true).build();
    31. // 将上面的配置信息 运用到这个Get请求里
    32. httpGet.setConfig(requestConfig);
    33. // 由客户端执行(发送)Get请求
    34. response = httpClient.execute(httpGet);
    35. // 从响应模型中获取响应实体
    36. HttpEntity responseEntity = response.getEntity();
    37. System.out.println("响应状态为:" + response.getStatusLine());
    38. if (responseEntity != null) {
    39. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    40. result=EntityUtils.toString(responseEntity);
    41. System.out.println("响应内容为:" + result);
    42. }
    43. } catch (ClientProtocolException e) {
    44. e.printStackTrace();
    45. } catch (ParseException e) {
    46. e.printStackTrace();
    47. } catch (IOException e) {
    48. e.printStackTrace();
    49. } finally {
    50. try {
    51. // 释放资源
    52. if (httpClient != null) {
    53. httpClient.close();
    54. }
    55. if (response != null) {
    56. response.close();
    57. }
    58. } catch (IOException e) {
    59. e.printStackTrace();
    60. }
    61. }
    62. return result;
    63. }

    2.提供者

    1. @RequestMapping("/get/youparam1")
    2. public String doGetYouParam(String name,Integer age){
    3. return "原来"+name+"都"+age+"岁";
    4. }

    3.调用

    2.3 get有参数:使用URI获得HttpGet

    1.消费者

    1. @RequestMapping("/hc/get/youcan2")
    2. public String yooucan2() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 参数
    6. URI uri = null;
    7. try {
    8. // 将参数放入键值对类NameValuePair中,再放入集合中
    9. List<NameValuePair> params = new ArrayList<>();
    10. params.add(new BasicNameValuePair("name", "lisi"));
    11. params.add(new BasicNameValuePair("age", "18"));
    12. // 设置uri信息,并将参数集合放入uri;
    13. // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
    14. uri = new URIBuilder().setScheme("http").setHost("localhost")
    15. .setPort(8082).setPath("/get/youparam2")
    16. .setParameters(params).build();
    17. } catch (URISyntaxException e1) {
    18. e1.printStackTrace();
    19. }
    20. // 创建Get请求
    21. HttpGet httpGet = new HttpGet(uri);
    22. // 响应模型
    23. CloseableHttpResponse response = null;
    24. String result="";
    25. try {
    26. // 配置信息
    27. RequestConfig requestConfig = RequestConfig.custom()
    28. // 设置连接超时时间(单位毫秒)
    29. .setConnectTimeout(5000)
    30. // 设置请求超时时间(单位毫秒)
    31. .setConnectionRequestTimeout(5000)
    32. // socket读写超时时间(单位毫秒)
    33. .setSocketTimeout(5000)
    34. // 设置是否允许重定向(默认为true)
    35. .setRedirectsEnabled(true).build();
    36. // 将上面的配置信息 运用到这个Get请求里
    37. httpGet.setConfig(requestConfig);
    38. // 由客户端执行(发送)Get请求
    39. response = httpClient.execute(httpGet);
    40. // 从响应模型中获取响应实体
    41. HttpEntity responseEntity = response.getEntity();
    42. System.out.println("响应状态为:" + response.getStatusLine());
    43. if (responseEntity != null) {
    44. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    45. result=EntityUtils.toString(responseEntity);
    46. System.out.println("响应内容为:" + result);
    47. }
    48. } catch (ClientProtocolException e) {
    49. e.printStackTrace();
    50. } catch (ParseException e) {
    51. e.printStackTrace();
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. } finally {
    55. try {
    56. // 释放资源
    57. if (httpClient != null) {
    58. httpClient.close();
    59. }
    60. if (response != null) {
    61. response.close();
    62. }
    63. } catch (IOException e) {
    64. e.printStackTrace();
    65. }
    66. }
    67. return result;
    68. }

    2.提供者

    1. @RequestMapping("/get/youparam2")
    2. public String doGetYouParam2(String name,Integer age){
    3. return "原来"+name+"都"+age+"岁";
    4. }

    3.调试

    三  实操实例Post方式

    3.1 post无参案例

    1.生产者

    1. @RequestMapping("/hc/post/wucan")
    2. public String doPostTestOne() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 创建Post请求
    6. HttpPost httpPost = new HttpPost("http://localhost:8082/post/noparam");
    7. // 响应模型
    8. CloseableHttpResponse response = null;
    9. String result="";
    10. try {
    11. // 由客户端执行(发送)Post请求
    12. response = httpClient.execute(httpPost);
    13. // 从响应模型中获取响应实体
    14. HttpEntity responseEntity = response.getEntity();
    15. System.out.println("响应状态为:" + response.getStatusLine());
    16. if (responseEntity != null) {
    17. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    18. result=EntityUtils.toString(responseEntity);
    19. System.out.println("响应内容为:" + result);
    20. }
    21. } catch (ClientProtocolException e) {
    22. e.printStackTrace();
    23. } catch (ParseException e) {
    24. e.printStackTrace();
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. } finally {
    28. try {
    29. // 释放资源
    30. if (httpClient != null) {
    31. httpClient.close();
    32. }
    33. if (response != null) {
    34. response.close();
    35. }
    36. } catch (IOException e) {
    37. e.printStackTrace();
    38. }
    39. }
    40. return result;
    41. }

    2.消费者

    1. @RequestMapping("/post/noparam")
    2. public String doPostNoParam(){
    3. return "post 请求无参数 123!";
    4. }

    3.调用

    3.2 post有参案例

    1.消费者

    1. @RequestMapping("/hc/post/youcan1")
    2. public String doPostTestFour() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 参数
    6. StringBuffer params = new StringBuffer();
    7. try {
    8. // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
    9. params.append("name=" + URLEncoder.encode("zhangsan", "utf-8"));
    10. params.append("&");
    11. params.append("age=24");
    12. } catch (UnsupportedEncodingException e1) {
    13. e1.printStackTrace();
    14. }
    15. // 创建Post请求
    16. HttpPost httpPost = new HttpPost("http://localhost:8082//post/youparam1" + "?" + params);
    17. // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
    18. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    19. // 响应模型
    20. CloseableHttpResponse response = null;
    21. String result="";
    22. try {
    23. // 由客户端执行(发送)Post请求
    24. response = httpClient.execute(httpPost);
    25. // 从响应模型中获取响应实体
    26. HttpEntity responseEntity = response.getEntity();
    27. System.out.println("响应状态为:" + response.getStatusLine());
    28. if (responseEntity != null) {
    29. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    30. result=EntityUtils.toString(responseEntity);
    31. System.out.println("响应内容为:" + result);
    32. }
    33. } catch (ClientProtocolException e) {
    34. e.printStackTrace();
    35. } catch (ParseException e) {
    36. e.printStackTrace();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. } finally {
    40. try {
    41. // 释放资源
    42. if (httpClient != null) {
    43. httpClient.close();
    44. }
    45. if (response != null) {
    46. response.close();
    47. }
    48. } catch (IOException e) {
    49. e.printStackTrace();
    50. }
    51. }
    52. return result;
    53. }

    2.消费者

    1. @RequestMapping(value="/post/youparam1",method = RequestMethod.POST)
    2. public String doPostYouParam(String name,Integer age){
    3. return "原来"+name+"都"+age+"岁";
    4. }

    3.调用

    3.3 post有参案例2 通过对象映射

    1.消费者

    1. @RequestMapping("/hc/post/youcan2")
    2. public String doPostTestTwo() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 创建Post请求
    6. HttpPost httpPost = new HttpPost("http://localhost:8082/post/youparam2");
    7. User user = new User();
    8. user.setName("潘晓婷");
    9. user.setAge(18);
    10. user.setGender("女");
    11. user.setMotto("姿势要优雅~");
    12. // 我这里利用阿里的fastjson,将Object转换为json字符串;
    13. // (需要导入com.alibaba.fastjson.JSON包)
    14. String jsonString = JSON.toJSONString(user);
    15. StringEntity entity = new StringEntity(jsonString, "UTF-8");
    16. // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
    17. httpPost.setEntity(entity);
    18. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    19. // 响应模型
    20. CloseableHttpResponse response = null;
    21. String result="";
    22. try {
    23. // 由客户端执行(发送)Post请求
    24. response = httpClient.execute(httpPost);
    25. // 从响应模型中获取响应实体
    26. HttpEntity responseEntity = response.getEntity();
    27. System.out.println("响应状态为:" + response.getStatusLine());
    28. if (responseEntity != null) {
    29. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    30. result=EntityUtils.toString(responseEntity);
    31. System.out.println("响应内容为:" + result);
    32. }
    33. } catch (ClientProtocolException e) {
    34. e.printStackTrace();
    35. } catch (ParseException e) {
    36. e.printStackTrace();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. } finally {
    40. try {
    41. // 释放资源
    42. if (httpClient != null) {
    43. httpClient.close();
    44. }
    45. if (response != null) {
    46. response.close();
    47. }
    48. } catch (IOException e) {
    49. e.printStackTrace();
    50. }
    51. }
    52. return result;
    53. }

    2.请求者

    1. @RequestMapping(value="/post/youparam2",method = RequestMethod.POST)
    2. public String doPostYouParam(@RequestBody User u){
    3. return u.toString();
    4. }

    3.调用

    3.4 post有参案例3 通过对象映射+参数

    1.消费者

    1. @RequestMapping("/hc/post/youcan3")
    2. public String doPostTestThree() {
    3. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
    4. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    5. // 创建Post请求
    6. // 参数
    7. URI uri = null;
    8. try {
    9. // 将参数放入键值对类NameValuePair中,再放入集合中
    10. List<NameValuePair> params = new ArrayList<>();
    11. params.add(new BasicNameValuePair("flag", "4"));
    12. params.add(new BasicNameValuePair("meaning", "这是什么鬼?"));
    13. // 设置uri信息,并将参数集合放入uri;
    14. // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
    15. uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8082)
    16. .setPath("/post/youparam3").setParameters(params).build();
    17. } catch (URISyntaxException e1) {
    18. e1.printStackTrace();
    19. }
    20. HttpPost httpPost = new HttpPost(uri);
    21. // HttpPost httpPost = new
    22. // HttpPost("http://localhost:12345/doPostControllerThree1");
    23. // 创建user参数
    24. User user = new User();
    25. user.setName("潘晓婷");
    26. user.setAge(18);
    27. user.setGender("女");
    28. user.setMotto("姿势要优雅~");
    29. // 将user对象转换为json字符串,并放入entity中
    30. StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
    31. // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
    32. httpPost.setEntity(entity);
    33. httpPost.setHeader("Content-Type", "application/json;charset=utf8");
    34. // 响应模型
    35. CloseableHttpResponse response = null;
    36. String result="";
    37. try {
    38. // 由客户端执行(发送)Post请求
    39. response = httpClient.execute(httpPost);
    40. // 从响应模型中获取响应实体
    41. HttpEntity responseEntity = response.getEntity();
    42. System.out.println("响应状态为:" + response.getStatusLine());
    43. if (responseEntity != null) {
    44. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
    45. result=EntityUtils.toString(responseEntity);
    46. System.out.println("响应内容为:" + result);
    47. }
    48. } catch (ClientProtocolException e) {
    49. e.printStackTrace();
    50. } catch (ParseException e) {
    51. e.printStackTrace();
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. } finally {
    55. try {
    56. // 释放资源
    57. if (httpClient != null) {
    58. httpClient.close();
    59. }
    60. if (response != null) {
    61. response.close();
    62. }
    63. } catch (IOException e) {
    64. e.printStackTrace();
    65. }
    66. }
    67. return result;
    68. }

    2.生产者

    1. @RequestMapping(value="/post/youparam3",method = RequestMethod.POST)
    2. public String doPostYouParam(@RequestBody User u,Integer flag,String meaning){
    3. return u.toString()+" flag:"+flag+" meaning:"+meaning;
    4. }

    3.调用

  • 相关阅读:
    数据结构学习笔记(V):树与二叉树
    Python爬虫实战:淘宝商品爬取与数据分析
    Hydra工具的使用
    架构设计杂谈
    vue-cli查看相关版本以及更新配置
    「Python实用秘技14」快速优化Python导包顺序
    ios ipa包上传需要什么工具
    线性插值方法
    qnx shell sh ,linux shell bash
    Leetcode 1758. 生成交替二进制字符串的最少操作数
  • 原文地址:https://blog.csdn.net/u011066470/article/details/134044002