2012-03-20 75 views
0

我目前正在研究一個移動應用程序,它將通過HTTP協議與RESTfull服務器進行通信。爲此,我制定了一個工作代碼,並讓溝通工作。HTTPclient和cookies的問題

爲了讓服務器識別用戶,我想使用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

你爲什麼不發送客戶端應用程序的唯一標記。這個令牌標識用戶,並且將每個請求發送給服務器? – 2012-03-20 15:53:00

+0

也許有點不清楚,代碼有點簡單 - 我嘗試發送一個名爲「X-ANDROID-USER」的cookie,值爲「some name」,所以服務器。 當我得到這個工作,我會改變「一些名字」爲一個獨特的價值。 – Etse 2012-03-20 15:56:47

回答

0

這個答案將幫助您:

How do I make an http request using cookies on Android?

//編輯

1)你的Android應用程序將它獨特的NFC的標籤到服務器。

2)服務器創建一個新的獨特的令牌,並建立一個releation beween單詞和NFC的標籤

3)當您的應用程序發送請求,發送獨特的NFC標籤了。

4)服務器將檢查NFC標籤和searchs令牌,現在你的設備識別

發送自定義標題:

HttpGet get = new HttpGet(getURL); 
get.addHeader("NFC", "YOUR NFC-TAG"); 
get.addHeader("Some more header", "more infos"); 
+0

嗨。感謝您的幫助。我已經通讀了它,它與我正在嘗試做的不同。他正在向服務器發出後請求並檢索發回的cookie。雖然我想在我的android應用程序上創建一個新的cookie(帶有從NFC標籤讀取的唯一標識符)。我想將此標籤作爲cookie發送。我是否真的需要向服務器發送後請求並讓服務器設置cookie? – Etse 2012-03-20 16:33:58

+0

剛剛編輯我的文章 – 2012-03-20 16:50:05

+0

這是我tryong做的。我甚至製作了烹飪器並添加到HttpContext中。當我提出請求時,我會告訴它使用這個上下文。 - 然而,標題永遠不會被髮送。 – Etse 2012-03-20 16:50:58