对于RestTemplate客户端和cookie感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解resttemplatecookie,并且为您提供关于FlashCookie【使用FlashC
对于RestTemplate客户端和cookie感兴趣的读者,本文将提供您所需要的所有信息,我们将详细讲解resttemplate cookie,并且为您提供关于Flash Cookie【使用Flash Cookie技术在客户端永久保存HTTP Cookie 】(一)、httpClient 和 RestTemplate 的使用、Mockito单元测试RestTemplate、org.springframework.boot.test.TestRestTemplate.HttpClientOption的实例源码的宝贵知识。
本文目录一览:- RestTemplate客户端和cookie(resttemplate cookie)
- Flash Cookie【使用Flash Cookie技术在客户端永久保存HTTP Cookie 】(一)
- httpClient 和 RestTemplate 的使用
- Mockito单元测试RestTemplate
- org.springframework.boot.test.TestRestTemplate.HttpClientOption的实例源码
RestTemplate客户端和cookie(resttemplate cookie)
我正在用Java编写一个简单的客户端,以允许可重用通过RESTful
API访问的专有病毒扫描软件。要上传文件以扫描API,需要先使用POST
Connect(连接),然后再要求将POST
文件发布到服务器。在对Connect的响应中,POST
服务器设置了cookie,随后将需要cookiePOST
来发布文件。我当前RestTemplate
在客户端中使用Spring 。
我的问题是我如何访问响应中的cookie,以便随后将其转发回服务器POST
?我可以看到它们存在于返回的标头中,但是没有ResponseEntity
访问它们的方法。
答案1
小编典典RestTemplate
有一个方法,您可以在其中定义InterfaceResponseExtractor<T>
,此接口用于获取响应的标头,一旦有了它们,就可以使用发送回来HttpEntity
并再次添加。
.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);
Flash Cookie【使用Flash Cookie技术在客户端永久保存HTTP Cookie 】(一)
前言:
在我负责的一个项目中,为了实现一个特殊的需求,要求在客户端的Cookie中长久保存一份数据,但是我们知道在客户端Cookie里保存数据是不稳定的,因为用户可能随时会清除掉浏览器的Cookie,在这种情况下,一般的解决方案是重新向服务器端发送一个请求,以获得一个新的HTTP Cookie数据,并将其保存--就一般的交互需求而言,这是没有问题的。但是,倘若我的需求是:要求恢复到原来的Cookie里保存数据呢?呵呵,这种情况,倘若服务器端没有做特殊的处理的话,显然是很难实现的。在尝试了许多方法之后,我们最后选择使用FlashCookie技术来做。
一、什么是Flash Cookie?
下面我首先来介绍一下FlashCookie。
FlashCookie是由FlashPlayer控制的客户端共享存储技术,它具备以下特点:1、类似HTTPCookie,FlashCookie利用Sharedobject类实现本地存储信息,Sharedobject类用于在用户计算机上读取和存储有限的数据量,共享对象提供永久贮存在用户计算机上的对象之间的实时数据共享;2、本地共享对象是作为一些单独的文件来存储的,它们的文件扩展名为.soL。默认时,它们的尺寸为不超过100kB,并且不会过期——这一点与传统的HTTP Cookie不同(4KB);3、本地共享对象并不是基于浏览器的,所以普通的用户不容易删除它们。如果要删掉它们的话,首先要知道这些文件所在的具体位置。这使得本地共享对象能够长时间的保留在本地系统上。
从上面可以看出,FlashCookie具有可操作性、比普通HTTPCookies有着更大存储空间、更好的隐蔽性等优点。加上现在FlashPlayer已经成为互联网用户标配之一,不存在兼容性的问题,因此它非常适合用来保护客户端数据、收集用户行为等。
根据加利福尼亚大学伯克利分校(University of California,Berkeley)的一项调查表明,目前全球Top100的网站中,至少有54家在使用Flash Cookie技术在进行用户行为收集,有兴趣的同学可以看看这篇文章:《Top websites using Flash cookies to track user behavior》
二、使用Flash Cookie永久存储HTTP Cookie流程
要实现Flash Cookie永远存储的功能,显然,首先要实现Flash Cookie与Http Cookie的互通,所以,在技术上使用JavaScript与ActionScript的来进行沟通显然是最好的选择,因为在这两种语言之间,除了语法上相近,从沟通上也有着完美的实现。下面我们来看看实现流程(如图所示):
三、ActionScript实现:
在明确了实现流程之后,那么接下来就是具体的实现了,首先是基础建设,在Flash端,我们使用的是ActionScript3来编程,下面实现了一个基本的Flash Cookies存储的类,在接下来的过程当中,我们将通过这个类来实现对Flash Cookies的操作。当然,这里只是把流程以及关键的技术讲清楚,涉及到具体的操作,则需要您自己来实现。
将所有的模块编译成SWF文件,我们将其命名为:hdl.swf,在上面的代码中,我们首先在构造函数里检查了Flash Cookie是否存在,如果存在,则会调用一个叫jsSetCookies的JavaScript方法来设置HTTP Cookie。那么,我们接下来要使用JavaScript来实现此SWF的调用以及互动。
四、JavaScript的实现:
1)首先要预定义一个供ActionScript3调用的方法,即上面说过的jsSetCookies方法。
2)检查特定的HTTPCookies是否存在,如果不存在,则在页面上生成Object Dom节点,把hdl.swf加载进来。此时SWF会去检查Flash Cookies是否存在,如果存在,则去取得Flash Cookies,并且通过调用jsSetCookies来设置HTTP Cookies:
倘若Flash Cookies里也没有存储我们想要的数据呢?那么,此时就必须通过JS去请求特定的URL,然后使用JavaScript去调用AS3的方法来设置Flash Cookies吧。关于这一步,就由大家自己去实现吧。呵呵。
五、结语:
那么到这里,基本上就实现了使用Flash Cookies来永久保存客户端数据的全过程。最后顺便说一下就是,其实这种方式也只能用来对付非计算机专业人士,因为Flash Cookie本身也是可以删除的,一般情况下,flash cookie保存在系统的如下位置:C:\Documents and Settings\yourusername\Application Data\Macromedia\Flash Player\#Sharedobjects\,如下图所示,一般情况下,在这个文件夹下可以看到很多的网站目录,里面有他们的Flash程序留下的痕迹:
当然,我这是删除过的,呵呵。
--EOF--
原文地址:http://www.handaoliang.com/article_tag/flash-cookie
httpClient 和 RestTemplate 的使用
1、httpClient 的使用
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
// 第一步:创建一个httpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 第二步:创建一个HttpPost对象。需要指定一个url
// HttpPost post = new HttpPost("http://47.244.48.xxx/xxx/xxx/");
HttpPost post = new HttpPost("http://127.0.0.1:8080/xxx/xxx/");
// 携带cookie
String sessionId = "PHPSESSID=KSoxfJlB20JJ0...";
BasicHeader header = new BasicHeader("Cookie", sessionId);
post.setHeader(header);
// 第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象
List<NameValuePair> formList = new ArrayList<>();
formList.add(new BasicNameValuePair("xxx", "xxx"));
formList.add(new BasicNameValuePair("xxx", "xxx"));
// 第四步:需要把表单数据包装到Entity对象中: StringEntity
StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8");
post.setEntity(entity);
// 第五步:执行请求。
CloseableHttpResponse response = httpClient.execute(post);
// 第六步:接收返回结果
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity);
System.out.println(result);
// 第七步:关闭流。
response.close();
httpClient.close();
2、RestTemplate 的使用:get 请求带 Cookie
String url = Config.XXX_BASE_URL + "/userlevel?inviterId=" + invit1;
String restInfo = MessageFormat.format("url:{0}, inviterId:{1}", url, invit1);
UtilFunctions.log.info("UserController#register call rest api info, " + restInfo);
HttpHeaders requestHeaders = new HttpHeaders();
List<String> cookieList = UtilFunctions.getCookieList(request);
requestHeaders.put("Cookie", cookieList);
HttpEntity<String> requestEntity = new HttpEntity<String>(null, requestHeaders);
restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class).getBody();
UtilFunctions 类的 getCookieList () 方法
public static List<String> getCookieList(HttpServletRequest request) {
List<String> cookieList = new ArrayList<>();
Cookie[] cookies = request.getCookies();
if (cookies == null || cookies.length == 0) {
return cookieList;
}
for (Cookie cookie : cookies) {
cookieList.add(cookie.getName() + "=" + cookie.getValue());
}
return cookieList;
}
参考资料:
1)Springboot — 用更优雅的方式发 HTTP 请求 (RestTemplate 详解)
Mockito单元测试RestTemplate
我正在使用RestTemplate
postForEntity
方法将正文发布到端点。我需要使用Mockito为我的代码编写测试用例的帮助。返回类型为void,但是可以将其更改为,Types
或者code
需要进行测试。我已经提到了许多其他文档,但是它们非常笼统,我尝试使用它们,但是由于request
and和return类型是不同的,所以大多数对我来说都不起作用。。任何建议表示赞赏。谢谢
这是我的Java课
public void postJson(Set<Type> Types){
try {
String oneString = String.join(",",Types);
Map<String,String> requestBody = new HashMap<>();
requestBody.put("type",oneString);
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(),null);
ResponseEntity result = restTemplate.exchange(url,HttpMethod.POST,new HttpEntity<>(request,getHttpHeaders()),String.class);
}
}
}
org.springframework.boot.test.TestRestTemplate.HttpClientOption的实例源码
@Test public void test_authenticate_success() throws JsonProcessingException { // authenticate HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); final String json = new ObjectMapper().writeValueAsstring( new UsernamePasswordToken(USER_EMAIL,USER_PWD)); System.out.println(json); final ResponseEntity<String> response = new TestRestTemplate( HttpClientOption.ENABLE_COOKIES).exchange(BASE_URL.concat("/auth"),HttpMethod.POST,new httpentity<>(json,headers),String.class); assertthat(response.getStatusCode(),equalTo(HttpStatus.OK)); }
@Test public void test_authenticate_failure() throws JsonProcessingException { // authenticate HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); final String json = new ObjectMapper().writeValueAsstring( new UsernamePasswordToken(USER_EMAIL,"wrong password")); System.out.println(json); final ResponseEntity<String> response = new TestRestTemplate( HttpClientOption.ENABLE_COOKIES).exchange(BASE_URL.concat("/auth"),equalTo(HttpStatus.OK)); }
@Test public void options() throws Exception { TestRestTemplate template = new TestRestTemplate( HttpClientOption.ENABLE_REDIRECTS); CustomHttpComponentsClientHttpRequestFactory factory = (CustomHttpComponentsClientHttpRequestFactory) template .getRequestFactory(); RequestConfig config = factory.getRequestConfig(); assertthat(config.isRedirectsEnabled(),equalTo(true)); }
@Test public void test_authenticate_success() throws JsonProcessingException { // authenticate HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); final String json = new ObjectMapper().writeValueAsstring( new UsernamePasswordToken(USER_EMAIL,equalTo(HttpStatus.OK)); }
@Test public void test_authenticate_failure() throws JsonProcessingException { // authenticate HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_JSON); final String json = new ObjectMapper().writeValueAsstring( new UsernamePasswordToken(USER_EMAIL,equalTo(HttpStatus.UNAUTHORIZED)); }
今天关于RestTemplate客户端和cookie和resttemplate cookie的介绍到此结束,谢谢您的阅读,有关Flash Cookie【使用Flash Cookie技术在客户端永久保存HTTP Cookie 】(一)、httpClient 和 RestTemplate 的使用、Mockito单元测试RestTemplate、org.springframework.boot.test.TestRestTemplate.HttpClientOption的实例源码等更多相关知识的信息可以在本站进行查询。
本文标签: