首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Spring RestTemplate执行设置http请求体?

如何使用Spring RestTemplate执行设置http请求体?
EN

Stack Overflow用户
提问于 2015-07-06 16:05:05
回答 1查看 8.7K关注 0票数 3

我想使用RestTemplate发出请求。我必须发送带有GET请求的请求有效负载。对-是的,我知道。因此,我尝试了RestTemplate.exchange,但似乎并不是发送GET请求的有效负载,不管发生什么。因此,我进一步查看了文档和数字,RestTemplate.execute可能是我要找的.现在我在这里

所以doc声明了执行

对给定的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请求?
EN

回答 1

Stack Overflow用户

发布于 2017-10-24 13:18:55

你可以这样做:

代码语言:javascript
复制
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。类似于:

代码语言:javascript
复制
restTemplate.execute(url, HttpMethod.POST, callback, responseExtractor);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31250534

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档