[英]RestTemplate: How to get the raw response
我正在使用 RestTemplate 访问服务。
RestTemplate rt = new RestTemplate ();
HttpEntity <String> he = new HttpEntity <String> (output, hh);
ResponseEntity <String> re = rt.exchange ("http://localhost:8080/my", HttpMethod.GET, he, String.class);
ResponseEntity具有用于访问响应的getBody和getHeaders 。 getHeaders已经是标题行的解析列表。
有没有办法可以将原始响应作为一大堆字节获得?
为此,您将使用以下execute
方法签名:
execute(URI url, HttpMethod method, RequestCallback requestCallback, ResponseExtractor<T> responseExtractor)
此方法将对给定 URL 执行 HTTP 方法,使用 RequestCallback 准备请求,并使用 ResponseExtractor 读取响应。
下一步是为ResponseExtractor接口编写一个自定义实现并覆盖负责从响应中提取数据的extractData()
。
这是示例。 首先,在控制器类中编写一些虚拟方法,如下所示:
@PostMapping(value = "/hello")
public String test() {
return "Hello world";
}
然后,编写将使用restTemplate
调用上述方法并将响应作为字节数组返回的方法:
@GetMapping("/test")
public void test() throws IOException {
final URI url = URI.create("http://localhost:8080/hello");
final Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
// Here you can set headers, request body,query parans,ect..
RequestCallback requestCallback = r -> {
//example: r.getBody().write(("username=" + username).getBytes());
r.getHeaders().setAll(headers);
};
byte[] res = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor<byte[]>() {
@Override
public byte[] extractData(ClientHttpResponse response) throws IOException {
byte[] data = new byte[1024];
// return data from response as byte array
response.getBody().read(data);
return data;
}
});
//write result in console
ByteArrayInputStream byteArrayInputStr
= new ByteArrayInputStream(res);
int b = 0;
while ((b = byteArrayInputStr.read()) != -1) {
char ch = (char) b;
System.out.println("Char : " + ch);
}
}
如果您执行test()
方法,您应该会看到如下输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.