带有 cookie 的 RestTemplate 客户端 [英] RestTemplate client with cookies
问题描述
我正在用 Java 编写一个简单的客户端,以允许重复使用可通过 RESTful API 访问的专有病毒扫描软件.要上传用于扫描 API 的文件,需要一个 POST
用于连接,然后是一个 POST
用于将文件发布到服务器.在对 Connect POST
的响应中,服务器设置了 cookie,这些 cookie 需要出现在随后的 POST
中以发布文件.我目前在我的客户端中使用 Spring RestTemplate
.
I'm writing a simple client in Java to allow reusable use of proprietary virus scanning software accessible through a RESTful API. To upload a file for scanning the API requires a POST
for Connect, followed by a POST
for Publishing the file to the server. In the response to the Connect POST
there are cookies set by the server which need to be present in the subsequent POST
for publishing the file. I'm currently using Spring RestTemplate
in my client.
我的问题是如何访问响应中的 cookie 以转发回带有后续 POST
的服务器?我可以看到它们存在于返回的标头中,但 ResponseEntity
上没有方法可以访问它们.
My question is how do I access the cookies in the response to forward back to the server with the subsequent POST
? I can see that they are present in the header that is returned but there are no methods on the ResponseEntity
to access them.
推荐答案
RestTemplate
有一个方法可以定义接口ResponseExtractor
,使用这个接口要获取响应的标头,一旦获得它们,您就可以使用 HttpEntity
将其发回并再次添加.
RestTemplate
has a method in which you can define Interface ResponseExtractor<T>
, this interface is used to obtain the headers of the response, once you have them you could send it back using HttpEntity
and added again.
.add("Cookie", "SERVERID=c52");
试试这样的方法.
String cookieHeader = null;
new ResponseExtractor<T>(){
T extractData(ClientHttpResponse response) {
response.getHeaders();
}
}
然后
HttpHeaders headers = new HttpHeaders();
headers.add("Cookie", cookieHeader );
ResponseEntity<byte[]> response = restTemplate.exchange("http://example.com/file/123",
GET,
new HttpEntity<String>(headers),
byte[].class);
另请阅读此帖子
这篇关于带有 cookie 的 RestTemplate 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!