【问题标题】:RestTemplate POST request RequestParams and RequestBodyRestTemplate POST 请求 RequestParams 和 RequestBody
【发布时间】:2023-03-19 18:00:01
【问题描述】:

我有一个服务器和一个客户端。我使用 Spring 在服务器上映射 http 请求,并使用 RestTemplate 向服务器发出请求。

服务器代码如下所示:

@RequestMapping (value="/someEndPoint", method = RequestMethod.POST)
@ResponseBody
public String configureSettings(
@RequestParam(required=false) Integer param1,
@RequestParam(required=false) Long param2,
@RequestBody String body)
{

if(param1 != null)
// do something

if(body not empty or null)
//do something

} 

客户端:

String postUrl = "http://myhost:8080/someEndPoint?param1=val1"
restTemplate.postForLocation(postUrl, null);

这会在服务器端从 param1 触发正确的操作 但是,请求的正文还包含:
参数 1=val1
设置的请求正文将是 json,所以我想要的只是能够在不设置正文的情况下设置其他参数。 我知道我使用 restTemplate 不正确,所以任何帮助将不胜感激。

【问题讨论】:

    标签: java spring resttemplate


    【解决方案1】:

    你正在做一个HTTP POST,但你没有提供一个对象来放置POSTed。 Spring的RestTemplate试图找出你想要POST的东西,所以它看起来并看到url的查询字符串有东西,所以它尝试使用它。

    不要将查询字符串添加到POST,只需提供您想要的对象POST

    String postUrl = "http://myhost:8080/someEndPoint"
    restTemplate.postForLocation(postUrl, new ParamModel("val1"));
    

    Spring in Action (3rd edition) 这本书很好地涵盖了RestTemplate(以及一般的 REST)。我建议你看看它。

    【讨论】:

      猜你喜欢
      • 2014-02-19
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 2011-05-03
      • 2018-11-19
      相关资源
      最近更新 更多