小编Reh*_*han的帖子

使用Spring RestTemplate时,REST POST可以正常使用POSTMAN,但是异常

我正在编写一个Rest客户端来使用Spring RestTemplate发布JSON数据.在正文中使用POSTMAN和跟随JSON数据获得正确的响应 -

{
    "InCode":"test",
    "Name":"This is  test",
    "Email":"test@gmail.com",
    "Id":18,
}
Run Code Online (Sandbox Code Playgroud)

但是,当尝试使用Spring RestTemplate按如下方式命中REST API时

ResponseEntity<String> response = restTemplate.exchange(baseUrl,
                HttpMethod.POST, getHeaders(), String.class);

private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
        request.put("Email", "test@gmail.com");
        request.put("Id", "18");
        request.put("Name", "This is  test");
        request.put("InCode", "test");

        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        return new HttpEntity<>(request.toString(), headers);
        }
Run Code Online (Sandbox Code Playgroud)

我得到例外 -

11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - …
Run Code Online (Sandbox Code Playgroud)

java rest spring resttemplate spring-rest

11
推荐指数
1
解决办法
3万
查看次数

TradeOff每次创建一个新的RestTemplate和创建一个返回相同的Rest模板的单个类

在Spring Boot中,用于在当前使用多个类中的new关键字创建RestTemplate的Rest Client调用.

RestTemplate restTemplate = new RestTemplate(); 
ResponseEntity<String> response = restTemplate.exchange(
Run Code Online (Sandbox Code Playgroud)

计划创建一个返回相同RestTemplate实例的类,并将其用于所有Rest调用.

它会影响性能吗?表演或其他任何可能的缺点?

而不是创建一个RestTemplate,使用Pooling更好的选择?谢谢

rest spring spring-mvc resttemplate spring-boot

8
推荐指数
1
解决办法
1188
查看次数