我目前正在开发一个移动应用程序,它将通过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?
答案 0 :(得分:0)
这个答案可以帮到你:
How do I make an http request using cookies on Android?
//编辑
1。)您的Android应用程序会将其唯一的NFC标签发送到服务器。
2。)服务器创建一个新的唯一令牌并在令牌和NFC标签之间建立关联
3。)每当您的应用发送请求时,也请发送唯一的NFC标签。
4.)服务器将检查NFC-Tag并搜索令牌,现在您的设备已被识别
发送自定义标题:
HttpGet get = new HttpGet(getURL);
get.addHeader("NFC", "YOUR NFC-TAG");
get.addHeader("Some more header", "more infos");