java 使用HttpClient发送@RequestBody类型的请求(解决中文乱码)
如何使用java发送参数以@RequestBody类型接收到的请求。如下使用java的HttpClient写一个样例
依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
1、接收部分代码
@RequestMapping("/test") public void getAccessToken(@RequestBody String jsonStr) { System.out.println("jsonStr:"+jsonStr); }
2、HttpClient发送的方法
public static String doPostRequestBody(String url, String jsonStr) { try { // 创建HttpClient实例 HttpClient client = HttpClients.createDefault(); // 创建HttpPost实例,指定URL HttpPost post = new HttpPost(url); // 设置请求头 post.setHeader("Content-Type", "application/json; charset=UTF-8"); post.setHeader("apiVersion", "v1"); // 设置请求体 StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8); post.setEntity(entity); // 发送请求 HttpResponse httpResponse = client.execute(post); // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "UTF-8")); String line = null; StringBuilder result = new StringBuilder(); while ((line = reader.readLine()) != null) { result.append(line); } // 打印响应内容 System.out.println("Response: " + result.toString()); return result.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
3、等同于postMan中的调用