我想使用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
所以,我有两个问题:
发布于 2017-10-24 13:18:55
你可以这样做:
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);https://stackoverflow.com/questions/31250534
复制相似问题