问题内容
httpclient调用本地其他服务,或者第三方系统接口,出现如下图问题:
准备内容
httpclient的maven依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
新建项目
1.新建一个SpringBoot项目
package com.example.temp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@SpringBootApplication
public class TempApplication {
@Description("模拟本地其他服务接口,或者第三方接口")
@PostMapping(path = "/postContent")
public void postContent(@RequestBody Map<String,Object> mapContent) {
System.out.println(mapContent);
}
public static void main(String[] args) {
SpringApplication.run(TempApplication.class, args);
}
}
2.新建一个客户端调用接口
package org.example;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class HttpClientDemo {
public static void main(String[] args) {
try {
String result = sendPOST();
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
private static String sendPOST() throws IOException {
String result = "";
HttpPost post = new HttpPost("http://localhost:8081/postContent");
// json content
String json = "{\n" +
" \"teslaKey\":\"teslaValue\",\n" +
" \"requestKey\":\"{\\\"customKey\\\":\\\"customValue\\\"}\"\n" +
"}";
System.out.println(json);
// send a JSON data
post.setEntity(new StringEntity(json));
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
result = EntityUtils.toString(response.getEntity());
}
return result;
}
}
运行结果
1.客户端调用SpringBoot项目接口,打印问题
{
"teslaKey":"teslaValue",
"requestKey":"{\"customKey\":\"customValue\"}"
}
{"timestamp":"2