使用Cookie的RestTemplate客户端 [英] RestTemplate client with cookies

查看:2283
本文介绍了使用Cookie的RestTemplate客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中编写一个简单的客户端,以允许可重复使用通过RESTful API访问的专有病毒扫描软件。要上传文件以扫描API,需要使用POST进行连接,然后执行POST以将文件发布到服务器。在对Connect POST的响应中,存在由服务器设置的cookie,它们需要存在于用于发布文件的后续POST中。我目前在我的客户端使用Spring RestTemplate。



我的问题是,如何访问响应中的cookie以转发回服务器,并进行后续的POST?我可以看到它们存在于返回的头中,但没有方法在ResponseEntity上访问它们。

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.

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.

推荐答案

Restemplate有一个方法,您可以在其中定义接口 ResponseExtractor< T> ,此接口用于获取响应的标题,一旦你有它们,你可以发回它使用HttpEntity并再次添加。

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

另请阅读此 post

这篇关于使用Cookie的RestTemplate客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆