[英]apache commons httpclient 4.23 form login problems different session cookies used in different requests
[英]Problems with HTTPclient and cookies
我目前正在开发一个移动应用程序,该应用程序将通过HTTP协议与RESTfull服务器进行通信。 为此,我编写了一个工作代码并使通信正常运行。
为了让服务器识别用户,我想使用cookie(某种会话cookie)。 因此,我从以下两个辅助方法开始,以创建HttpClient和上下文(包括我的cookie)。
// Gets a standard client - set to HTTP1.1
private HttpClient getClient() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
return new DefaultHttpClient(params);
}
// Gets the context with cookies to be used. This is to make each user unique
private HttpContext getHttpContext(String server) {
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("X-ANDROID-USER", "some name");
cookie.setDomain(server);
cookie.setPath("/");
cookie.setVersion(1);
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
return localContext;
}
然后,我使用以下(读取功能)连接到服务器。 基本上,这需要使用Client和Conext的后两个辅助方法生成并执行正常的GET请求。
//连接到restfull服务器并返回返回值(获取请求)
private String restfullRead(URI uri, String server) { // Sets up the different objects needed to read a HttpRequest HttpClient client = this.getClient(); HttpGet request = new HttpGet(); request.setURI(uri); HttpContext context = this.getHttpContext(server); // Connects to the server and reads response try { HttpResponse response = client.execute(request, context); reader.close(); } catch (Exception e) { return ""; }
When I run this to my server I get the following request.
GET /info/1 HTTP/1.1
Host: 192.168.0.191:8080
Connection: Keep-Alive
如您所见,其中不包含任何cookie。 那就是为什么我想知道,为什么不在请求中发送“ getHttpContext”中生成的cookie?
该答案将帮助您:
//编辑
1.)您的Android应用将其唯一的NFC标签发送到服务器。
2.)服务器创建一个新的唯一令牌,并在令牌和NFC-Tag之间建立关系
3.)每当您的应用发送请求时,也发送唯一的NFC标签。
4.)服务器将检查NFC标签并搜索令牌,现在可以识别您的设备
发送自定义标头:
HttpGet get = new HttpGet(getURL);
get.addHeader("NFC", "YOUR NFC-TAG");
get.addHeader("Some more header", "more infos");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.