![](/img/trans.png)
[英]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.