当前位置:   article > 正文

使用HttpClient发送Http请求详细示例

httpclient发送http请求

目录

一、GET无参,HTTP发送示例

二、GET有参(方式一:拼接URL参数)

三、GET有参(方式二:使用URI方式)

四、POST有参(对象+普通参数)

五、application/x-www-form-urlencoded表单请求(示例)

知识补充:application/x-www-form-urlencoded和multipart/form-data

(1)application/x-www-urlencoded

(3)multipart/form-data

六、发送文件示例

七、发送流示例


HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

HTTP和浏览器有点像,但却不是浏览器。很多人觉得既然HttpClient是一个HTTP客户端编程工具,很多人把他当做浏览器来理解,但是其实HttpClient不是浏览器,它是一个HTTP通信库,因此它只提供一个通用浏览器应用程序所期望的功能子集,最根本的区别是HttpClient中没有用户界面,浏览器需要一个渲染引擎来显示页面,并解释用户输入,例如鼠标点击显示页面上的某处,有一个布局引擎,计算如何显示HTML页面,包括级联样式表和图像。javascript解释器运行嵌入HTML页面或从HTML页面引用的javascript代码。来自用户界面的事件被传递到javascript解释器进行处理。除此之外,还有用于插件的接口,可以处理Applet,嵌入式媒体对象(如pdf文件,Quicktime电影和Flash动画)或ActiveX控件(可以执行任何操作)。HttpClient只能以编程的方式通过其API用于传输和接受HTTP消息。

在使用HttpClient前,首先需要导入其maven依赖,另外还引入了fastjson的依赖,在示例中会用到

  1. <dependency>
  2. <groupId>org.apache.httpcomponents</groupId>
  3. <artifactId>httpclient</artifactId>
  4. <version>4.5.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.58</version>
  10. </dependency>

本文示例使用springboot的运行环境,springboot运行环境的搭建请参照我的这篇文章:快速构建一个springboot项目

在运行测试案例前需要先启动springboot项目,然后再启动测试类进行测试,如果不知道怎样搭建springboot的单元测试,可以参照我的这篇文章:编写springboot单元测试类

以下所有示例亲测有效。

一、GET无参,HTTP发送示例

代码示例:

  1. /**
  2. * GET---无参测试
  3. */
  4. @Test
  5. public void doGetNoParam() {
  6. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
  7. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  8. // 创建Get请求
  9. HttpGet httpGet = new HttpGet("http://localhost:8080/http/doGetNoParam");
  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. System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
  21. }
  22. } catch (ClientProtocolException e) {
  23. e.printStackTrace();
  24. } catch (ParseException e) {
  25. e.printStackTrace();
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. } finally {
  29. try {
  30. // 释放资源
  31. if (httpClient != null) {
  32. httpClient.close();
  33. }
  34. if (response != null) {
  35. response.close();
  36. }
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }

对应的接收示例:

  1. @RequestMapping("doGetNoParam")
  2. public String doGetNoParam(){
  3. return "doGetNoParam...";
  4. }

执行结果:

二、GET有参(方式一:拼接URL参数)

代码示例:

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

对应接收示例:

  1. @GetMapping("/doGetAppendUrl")
  2. public String doGetAppendUrl(String name,Integer age){
  3. return name + ",ta的年龄为" + age + "岁了";
  4. }

执行结果:

三、GET有参(方式二:使用URI方式)

代码示例:

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

对应的接收示例跟上边方法一是一样的,在此就不过多描述了。

四、POST有参(对象+普通参数)

POST无参基本上跟GET传参差不多,就是new HttpPost()而已。Post传基本参数,可以通过拼接Url的方式,也可以使用URI的方式,此示例把对象传参和基本传参结合在一起,以便囊括常用的传参方式。

使用URI传递普通参数,使用Entity传递对象参数,其中用到的User对象是自己创建的简单对象类型,里边有一些Get和Set方法,在此就不一一列举了。

代码示例:

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

防止响应乱码,可以主动设置编码

String response = EntityUtils.toString(responseEntity, UTF_8);

对应接收示例:

  1. @PostMapping("/doPostUseParam")
  2. public String doPostUseParam(@RequestBody User user, String meaning, Integer flag) {
  3. return user.getUserName() + ",ta是" + user.getUserSex() + "生。这意味着" + meaning + flag;
  4. }

执行结果:

五、application/x-www-form-urlencoded表单请求(示例)

代码示例:

  1. /**
  2. * POST---application/x-www-form-urlencoded 表单请求
  3. */
  4. @Test
  5. public void doPostUseForm() {
  6. // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
  7. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  8. HttpPost httpPost = new HttpPost("http://localhost:8080/http/doPostUseForm");
  9. httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
  10. // 将参数放入键值对类NameValuePair中,再放入集合中
  11. List<NameValuePair> params = new ArrayList<>();
  12. params.add(new BasicNameValuePair("bookName", "语文"));
  13. params.add(new BasicNameValuePair("message", "这是一本好书"));
  14. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, UTF_8);
  15. httpPost.setEntity(formEntity);
  16. CloseableHttpResponse response = null;
  17. try {
  18. // 由客户端执行(发送)Post请求
  19. response = httpClient.execute(httpPost);
  20. // 从响应模型中获取响应实体
  21. HttpEntity responseEntity = response.getEntity();
  22. System.out.println("响应状态为:" + response.getStatusLine());
  23. if (responseEntity != null) {
  24. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  25. System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
  26. }
  27. } catch (ClientProtocolException e) {
  28. e.printStackTrace();
  29. } catch (ParseException e) {
  30. e.printStackTrace();
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. } finally {
  34. try {
  35. // 释放资源
  36. if (httpClient != null) {
  37. httpClient.close();
  38. }
  39. if (response != null) {
  40. response.close();
  41. }
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. }

对应接收示例:

  1. @PostMapping("/doPostUseForm")
  2. public String doPostUseForm(String bookName, String message) {
  3. return bookName + ":" + message;
  4. }

知识补充:application/x-www-form-urlencoded和multipart/form-data

一个 HTML 表单中的 enctype 有三种类型

  • application/x-www-urlencoded
  • multipart/form-data
  • text-plain

默认情况下是 application/x-www-urlencoded,当表单使用 POST 请求时,数据会被以 x-www-urlencoded 方式编码到 Body 中来传送,而如果 GET 请求,则是附在 url 链接后面来发送。GET 请求只支持 ASCII 字符集,因此,如果我们要发送更大字符集的内容,我们应使用 POST 请求。
如果要发送大量的二进制数据(non-ASCII),application/x-www-form-urlencoded 显然是低效的,因为它需要用 3 个字符来表示一个 non-ASCII 的字符。因此,这种情况下,应该使用 “multipart/form-data” 格式。

application / x-www-form-urlencoded对于发送大量二进制数据或包含非ASCII字符的文本效率低下

multipart / form-data应该用于提交包含文件,非ASCII数据和二进制数据的表单

(1)application/x-www-urlencoded

我们在通过 HTTP 向服务器发送 POST 请求提交数据,都是通过 form 表单形式提交的,代码如下:

  1. <FORM method="post" action="http://w.sohu.com" >
  2. <INPUT type="text" name="txt1">
  3. <INPUT type="text" name="txt2">
  4. </FORM>

提交时会向服务器端发出这样的数据(已经去除部分不相关的头信息),数据如下:

  1. POST / HTTP/1.1
  2. Content-Type:application/x-www-form-urlencoded
  3. Accept-Encoding: gzip, deflate
  4. Host: w.sohu.com
  5. Content-Length: 21
  6. Connection: Keep-Alive
  7. Cache-Control: no-cache
  8. txt1=hello&txt2=world

对于普通的 HTML Form POST请求,它会在头信息里使用 Content-Length 注明内容长度。请求头信息每行一条,空行之后便是 Body,即“内容”(entity。内容的格式是在头信息中的 Content-Type 指定的,如上是 application/x-www-form-urlencoded,这意味着消息内容会经过 URL 格式编码,就像在 GET请 求时 URL 里的 QueryString 那样。如:txt1=hello&txt2=world。

(3)multipart/form-data

multipart/form-data 定义在 rfc2388 中,最早的 HTTP POST 是不支持文件上传的,给编程开发带来很多问题。但是在1995年,ietf 出台了 rfc1867,也就是《RFC 1867 -Form-based File Upload in HTML》,用以支持文件上传。所以 Content-Type 的类型扩充了multipart/form-data 用以支持向服务器发送二进制数据。因此,发送 POST 请求时候,表单 属性 enctype 共有二个值可选,这个属性管理的是表单的 MIME 编码:

  • ① application/x-www-form-urlencoded (默认值)
  • ② multipart/form-data

注:form 表单中 enctype 的默认值是 enctype="application/x- www-form-urlencoded".
通过 form 表单提交文件操作如下:

  1. <FORM method="POST" action="http://w.sohu.com/t2/upload.do" enctype="multipart/form-data">
  2. <INPUT type="text" name="city" value="Santa colo">
  3. <INPUT type="text" name="desc">
  4. <INPUT type="file" name="pic">
  5. </FORM>

浏览器将会发送以下数据:

  1. POST /t2/upload.do HTTP/1.1
  2. User-Agent: SOHUWapRebot
  3. Accept-Language: zh-cn,zh;q=0.5
  4. Accept-Charset: GBK,utf-8;q=0.7,*;q=0.7
  5. Connection: keep-alive
  6. Content-Length: 60408
  7. Content-Type:multipart/form-data; boundary=ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
  8. Host: w.sohu.com
  9. --ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
  10. Content-Disposition: form-data; name="city"
  11. Santa colo
  12. --ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
  13. Content-Disposition: form-data;name="desc"
  14. Content-Type: text/plain; charset=UTF-8
  15. Content-Transfer-Encoding: 8bit
  16. ...
  17. --ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC
  18. Content-Disposition: form-data;name="pic"; filename="photo.jpg"
  19. Content-Type: application/octet-stream
  20. Content-Transfer-Encoding: binary
  21. ... binary data of the jpg ...
  22. --ZnGpDtePMx0KrHh_G0X99Yef9r8JZsRJSXC--

从上面的 multipart/form-data 格式发送的请求的样式来看,它包含了多个 Parts,每个 Part 都包含头信息部分,
Part 头信息中必须包含一个 Content-Disposition 头,其他的头信息则为可选项, 比如 Content-Type 等。
Content-Disposition 包含了 type 和 一个名字为 name 的 parameter,type 是 form-data,name 参数的值则为表单控件(也即 field)的名字,如果是文件,那么还有一个 filename 参数,值就是文件名。对于可选的 Content-Type(如果没有的话),默认就是 text/plain。

注意:
如果文件内容是通过填充表单来获得,那么上传的时候,Content-Type 会被自动设置(识别)成相应的格式,如果没法识别,那么就会被设置成 application/octet-stream”。

六、发送文件示例

如果想要灵活方便的传输文件的话,除了引入org.apache.httpcomponents基本的httpclient依赖外再额外引入org.apache.httpcomponents的httpmime依赖。
P.S.:即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。

在pom.xml中额外引入:

  1. <!--如果需要灵活的传输文件,引入此依赖后会更加方便-->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents</groupId>
  4. <artifactId>httpmime</artifactId>
  5. <version>4.5.5</version>
  6. </dependency>

代码示例:

  1. /**
  2. *
  3. * 发送文件
  4. *
  5. * multipart/form-data传递文件(及相关信息)
  6. *
  7. * 注:如果想要灵活方便的传输文件的话,
  8. * 除了引入org.apache.httpcomponents基本的httpclient依赖外
  9. * 再额外引入org.apache.httpcomponents的httpmime依赖。
  10. * 追注:即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。
  11. *
  12. */
  13. @Test
  14. public void doPostUseFile() {
  15. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  16. HttpPost httpPost = new HttpPost("http://localhost:8080/http/doPostUseFile");
  17. CloseableHttpResponse response = null;
  18. try {
  19. MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
  20. // 第一个文件
  21. String filesKey = "files";
  22. File file1 = new File("D:\\MyFiles\\poi\\picture.jpg");
  23. multipartEntityBuilder.addBinaryBody(filesKey, file1);
  24. // 第二个文件(多个文件的话,使用同一个key就行,后端用数组或集合进行接收即可)
  25. File file2 = new File("D:\\MyFiles\\poi\\图片.jpg");
  26. // 防止服务端收到的文件名乱码。 我们这里可以先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。
  27. // 文件名其实是放在请求头的Content-Disposition里面进行传输的,如其值为form-data; name="files"; filename="头像.jpg"
  28. multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "utf-8"));
  29. // 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
  30. ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
  31. multipartEntityBuilder.addTextBody("name", "邓沙利文", contentType);
  32. multipartEntityBuilder.addTextBody("age", "25", contentType);
  33. HttpEntity httpEntity = multipartEntityBuilder.build();
  34. httpPost.setEntity(httpEntity);
  35. response = httpClient.execute(httpPost);
  36. HttpEntity responseEntity = response.getEntity();
  37. System.out.println("HTTPS响应状态为:" + response.getStatusLine());
  38. if (responseEntity != null) {
  39. System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength());
  40. // 主动设置编码,来防止响应乱码
  41. String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
  42. System.out.println("HTTPS响应内容为:" + responseStr);
  43. }
  44. } catch (ParseException | IOException e) {
  45. e.printStackTrace();
  46. } finally {
  47. try {
  48. // 释放资源
  49. if (httpClient != null) {
  50. httpClient.close();
  51. }
  52. if (response != null) {
  53. response.close();
  54. }
  55. } catch (IOException e) {
  56. e.printStackTrace();
  57. }
  58. }
  59. }

对应的接收示例:

  1. @PostMapping("/doPostUseFile")
  2. public String doPostUseFile(@RequestParam("name") String name,
  3. @RequestParam("age") Integer age,
  4. @RequestParam("files") List<MultipartFile> multipartFiles) throws UnsupportedEncodingException {
  5. StringBuilder sb = new StringBuilder();
  6. sb.append("\n");
  7. sb.append("name=").append(name)
  8. .append("\tage=").append(age);
  9. String fileName;
  10. for(MultipartFile file : multipartFiles){
  11. sb.append("\n文件信息:\n");
  12. fileName = file.getOriginalFilename();
  13. if(fileName == null){
  14. continue;
  15. }
  16. // 防止中文乱码问题
  17. fileName = URLDecoder.decode(fileName, "utf-8");
  18. sb.append("\t文件名:").append(fileName);
  19. sb.append("\t文件大小:").append(file.getSize() * 1.0 /1024).append("KB");
  20. sb.append("\tContentType:").append(file.getContentType());
  21. sb.append("\n");
  22. }
  23. return sb.toString();
  24. }

执行结果:

七、发送流示例

代码示例:

  1. /**
  2. * 发送流
  3. */
  4. @Test
  5. public void doPostUseStream() {
  6. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  7. HttpPost httpPost = new HttpPost("http://localhost:8080/http/doPostUseStream?name=邓沙利文");
  8. CloseableHttpResponse response = null;
  9. try {
  10. InputStream stream = new ByteArrayInputStream("流啊流~".getBytes());
  11. InputStreamEntity InputStream = new InputStreamEntity(stream);
  12. httpPost.setEntity(InputStream);
  13. response = httpClient.execute(httpPost);
  14. HttpEntity responseEntity = response.getEntity();
  15. System.out.println("HTTPS响应状态为:" + response.getStatusLine());
  16. if (responseEntity != null) {
  17. System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength());
  18. // 主动设置编码,来防止响应乱码
  19. String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
  20. System.out.println("HTTPS响应内容为:" + responseStr);
  21. }
  22. } catch (ParseException | IOException e) {
  23. e.printStackTrace();
  24. } finally {
  25. try {
  26. // 释放资源
  27. if (httpClient != null) {
  28. httpClient.close();
  29. }
  30. if (response != null) {
  31. response.close();
  32. }
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }

接收端示例:

  1. @PostMapping("/doPostUseStream")
  2. public String doPostUseStream(@RequestParam("name") String name,
  3. InputStream stream) throws IOException {
  4. StringBuilder sb = new StringBuilder();
  5. sb.append("\nname值为:").append(name);
  6. sb.append("\n输入数据流内容为:");
  7. BufferedReader bf = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
  8. String line;
  9. while((line = bf.readLine()) != null){
  10. sb.append(line);
  11. }
  12. return sb.toString();
  13. }

执行结果:

最后总结一下:使用HttpClient发送HTTP请求基本分为四步:

  1. 创建Http客户端
  2. 创建request请求
  3. 执行Reuest请求
  4. 关闭资源
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/217781
推荐阅读
相关标签
  

闽ICP备14008679号