spring - 如何使用Spring RestTemplate执行设置http请求正文?

标签 spring spring-mvc get spring-3 resttemplate

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

因此文档说明了执行:

Execute the HTTP method to the given URI template, preparing the request with the RequestCallback, and reading the response with a ResponseExtractor.

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

好的。让我们看看RequestCallback

Callback interface for code that operates on a ClientHttpRequest. Allows to manipulate the request headers, and write to the request body. Used internally by the RestTemplate, but also useful for application code.

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

但是RequestCallback只有一个方法:doWithRequest,它通过ClientHttpRequest接口(interface)接受它的参数...它没有设置方法/操纵请求的正文。可悲的是。 :C

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

所以,我有两个问题:

  • 关于文档,我缺少什么?
  • 如何使用 RestTemplate 发出带有负载/请求正文的 GET 请求?

最佳答案

你可以这样做:

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);

关于spring - 如何使用Spring RestTemplate执行设置http请求正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250534/

相关文章:

java - Spring 3.0 Java REST返回PDF文档

java - Spring mvc - REST webservice - 一个 api 是可调用的,另一个报告 "No mapping found for HTTP request with URI"

java - spring mvc+ajax 获取点击数据

php - 从 MySQL 存储和检索 $_GET 语句

spring - 多个 application.yml 未在 Spring Boot 中合并

java - 当参数为 null 作为参数时

spring-mvc - 在 Spring MVC 3 中处理后重定向时, session 属性是否显示在 URL 中?

java - 根据 Spring 配置文件注册不同的流

php - 使用 $.load() 发送 'GET' 数据

javascript - 使用 JavaScript 或 jQuery 构建带有 GET 参数的链接的最佳方式是什么