参考文章:https://blog.csdn.net/justry_deng/article/details/81042379 pom
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency>请求
@Test void test1() { // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Get请求 HttpGet httpGet = new HttpGet("http://localhost:8080/test1"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); // 获得输入流,内容在输入流中 // InputStream content = responseEntity.getContent(); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@GetMapping("/test1") public List<String> test1(){ List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); return list; }发送
@Test void test2() { // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数 StringBuffer params = new StringBuffer(); try { // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去) params.append("name=" + URLEncoder.encode("&", "utf-8")); params.append("&"); params.append("age=24"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 创建Get请求 HttpGet httpGet = new HttpGet("http://localhost:8080/test2" + "?" + params); // 响应模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(5000) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(5000) // socket读写超时时间(单位毫秒) .setSocketTimeout(5000) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里 httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
// 一 @GetMapping("/test2") public String test2(String name,Integer age){ System.out.println("姓名:"+name+"年龄:"+age); return "好的"; } // 二 @GetMapping("/test2") public String test2(User user){ System.out.println(user); return "好的"; }请求
@Test void test3() { // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数 URI uri = null; try { // 将参数放入键值对类NameValuePair中,再放入集合中 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("name", "&")); params.add(new BasicNameValuePair("age", "18")); // 设置uri信息,并将参数集合放入uri; // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme("http").setHost("localhost") .setPort(8080).setPath("/test2") .setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } // 创建Get请求 HttpGet httpGet = new HttpGet(uri); // 响应模型 CloseableHttpResponse response = null; try { // 配置信息 RequestConfig requestConfig = RequestConfig.custom() // 设置连接超时时间(单位毫秒) .setConnectTimeout(5000) // 设置请求超时时间(单位毫秒) .setConnectionRequestTimeout(5000) // socket读写超时时间(单位毫秒) .setSocketTimeout(5000) // 设置是否允许重定向(默认为true) .setRedirectsEnabled(true).build(); // 将上面的配置信息 运用到这个Get请求里 httpGet.setConfig(requestConfig); // 由客户端执行(发送)Get请求 response = httpClient.execute(httpGet); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }请求
@Test void test4(){ // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Post请求 HttpPost httpPost = new HttpPost("http://localhost:8080/test4"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test4") public String test4(){ return "good"; }请求
@Test void test5() { // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 参数 StringBuffer params = new StringBuffer(); try { // 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去) params.append("name=" + URLEncoder.encode("&", "utf-8")); params.append("&"); params.append("age=24"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 创建Post请求 HttpPost httpPost = new HttpPost("http://localhost:8080/test5" + "?" + params); // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json) httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test5") public User test5(User user){ return user; }请求
@Test void test6(){ // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Post请求 HttpPost httpPost = new HttpPost("http://localhost:8080/test5"); User user = new User(); user.setName("潘晓婷"); user.setAge(18); // 我这里利用阿里的fastjson,将Object转换为json字符串; String jsonString = JSON.toJSONString(user); StringEntity entity = new StringEntity(jsonString, "UTF-8"); // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中 httpPost.setEntity(entity); httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test5") public User test5(@RequestBody User user){ return user; }发送
@Test void test7(){ // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的) CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // 创建Post请求 // 参数 URI uri = null; try { // 将参数放入键值对类NameValuePair中,再放入集合中 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("flag", "4")); params.add(new BasicNameValuePair("meaning", "这是什么鬼?")); // 设置uri信息,并将参数集合放入uri; // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value) uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(8080) .setPath("/test7").setParameters(params).build(); } catch (URISyntaxException e1) { e1.printStackTrace(); } HttpPost httpPost = new HttpPost(uri); // 创建user参数 User user = new User(); user.setName("潘晓婷"); user.setAge(18); // 将user对象转换为json字符串,并放入entity中 StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8"); // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中 httpPost.setEntity(entity); httpPost.setHeader("Content-Type", "application/json;charset=utf8"); // 响应模型 CloseableHttpResponse response = null; try { // 由客户端执行(发送)Post请求 response = httpClient.execute(httpPost); // 从响应模型中获取响应实体 HttpEntity responseEntity = response.getEntity(); System.out.println("响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("响应内容长度为:" + responseEntity.getContentLength()); System.out.println("响应内容为:" + EntityUtils.toString(responseEntity)); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test7") public User test7(@RequestBody User user,Integer flag,String meaning){ System.out.println(user.toString() + flag + meaning); return user; }引入依赖
<!--更方便的处理文件--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.12</version> </dependency> @Test void test8(){ CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://localhost:8080/test8"); CloseableHttpResponse response = null; try { MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); // 第一个文件 String filesKey = "files"; File file1 = new File("e:\\test\\back.jpg"); multipartEntityBuilder.addBinaryBody(filesKey, file1); // 第二个文件(多个文件的话,使用同一个key就行,后端用数组或集合进行接收即可) File file2 = new File("e:\\test\\头像.jpg"); // 防止服务端收到的文件名乱码。 我们这里可以先将文件名URLEncode,然后服务端拿到文件名时在URLDecode。就能避免乱码问题。 // 文件名其实是放在请求头的Content-Disposition里面进行传输的,如其值为form-data; name="files"; filename="头像.jpg" multipartEntityBuilder.addBinaryBody(filesKey, file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(), "UTF-8")); // 其它参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码) ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); multipartEntityBuilder.addTextBody("name", "邓沙利文", contentType); multipartEntityBuilder.addTextBody("age", "25", contentType); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("HTTPS响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength()); // 主动设置编码,来防止响应乱码 String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); System.out.println("HTTPS响应内容为:" + responseStr); } } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test8") public void test8(String name, Integer age,@RequestParam("files") List<MultipartFile> multipartFileList) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); sb.append("姓名:").append(name).append("年龄:").append(age); for (MultipartFile file : multipartFileList) { if (file == null) { continue; } sb.append("文件名:"). append( // 防止乱码 URLEncoder.encode(file.getOriginalFilename(),"UTF-8")); sb.append("大小:").append(file.getSize()*1.0/1024).append("KB"); sb.append("ContentType").append(file.getContentType()); } System.out.println(sb.toString()); }发送
@Test void test9(){ CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://localhost:8080/test9?name=邓沙利文"); CloseableHttpResponse response = null; try { InputStream is = new ByteArrayInputStream("流啊流~".getBytes()); InputStreamEntity ise = new InputStreamEntity(is); httpPost.setEntity(ise); response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("HTTPS响应状态为:" + response.getStatusLine()); if (responseEntity != null) { System.out.println("HTTPS响应内容长度为:" + responseEntity.getContentLength()); // 主动设置编码,来防止响应乱码 String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8); System.out.println("HTTPS响应内容为:" + responseStr); } } catch (ParseException | IOException e) { e.printStackTrace(); } finally { try { // 释放资源 if (httpClient != null) { httpClient.close(); } if (response != null) { response.close(); } } catch (IOException e) { e.printStackTrace(); } } }接收
@PostMapping("/test9") public void test9(String name, InputStream is) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("名字:").append(name).append("\n"); sb.append("输入流:"); try ( BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); ) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); }finally { if (is != null){ is.close(); } } System.out.println(sb.toString()); }