【问题标题】:How to set http request body using Spring RestTemplate execute?如何使用 Spring RestTemplate 执行设置 http 请求正文?
【发布时间】:2015-07-06 16:05:05
【问题描述】:

我想使用 RestTemplate 来发出请求。我必须使用 GET 请求发送请求有效负载。是的,是的,我知道。所以我尝试了 RestTemplate.exchange,但无论如何它似乎都没有发送 GET 请求的有效负载。所以我进一步查看了文档和数字 RestTemplate.execute 可能是我正在寻找的......现在我在这里。

所以文档说明了执行

对给定的 URI 模板执行 HTTP 方法,使用 RequestCallback 准备请求,并使用 ResponseExtractor 读取响应。

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/web/client/RestTemplate.html

好的。让我们看看 RequestCallback

ClientHttpRequest 上运行的代码的回调接口。允许操作请求标头,并写入请求正文。 RestTemplate 内部使用,但对应用程序代码也很有用。

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/web/client/RequestCallback.html

但是RequestCallback只有一种方法:doWithRequest,它通过ClientHttpRequest接口接受它的参数...它没有设置方法/ 操作请求的主体。可悲的是。 :C

http://docs.spring.io/spring-framework/docs/3.2.8.RELEASE/javadoc-api/org/springframework/http/client/ClientHttpRequest.html

所以,我有两个问题:

  • 关于文档,我在这里遗漏了什么?
  • 如何使用 RestTemplate 发出带有负载/请求正文的 GET 请求?

【问题讨论】:

  • 对对对,我知道:那你为什么要这么做? GET 请求不应该有有效载荷。也就是说,ClientHttpRequest 有一个 getBody() 方法。那么,有什么问题呢?
  • “是的,是的,我知道。”不过,任何有用的想法都会很好!
  • 你是怎么做到的?我需要存根与服务器的连接并将其替换为静态的 restTemplate。我需要请求使用预定义的 restTemplate 并在组件测试期间将响应发送到应用程序。

标签: spring spring-mvc get spring-3 resttemplate


【解决方案1】:

你可以这样做:

public class BodySettingRequestCallback implements RequestCallback {

    private String body;
    private ObjectMapper objectMapper;

    public BodySettingRequestCallback(String body, ObjectMapper objectMapper){
        this.body = body;
        this.objectMapper = objectMapper;
    }

    @Override
    public void doWithRequest(ClientHttpRequest request) throws IOException {
      byte[] json = getEventBytes();
      request.getBody().write(json);
    }

    byte[] getEventBytes() throws JsonProcessingException {
        return objectMapper.writeValueAsBytes(body);
    }
}

您将在您的执行方法中使用此 RequestCallback。比如:

restTemplate.execute(url, HttpMethod.POST, callback, responseExtractor);

【讨论】:

  • 这里的映射器是什么?
  • 很好,它是一个 ObjectMapper。会编辑。谢谢。
猜你喜欢
  • 2016-09-21
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
相关资源
最近更新 更多