我目前正在研究一個移動應用程序,它將通過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?
你爲什麼不發送客戶端應用程序的唯一標記。這個令牌標識用戶,並且將每個請求發送給服務器? – 2012-03-20 15:53:00
也許有點不清楚,代碼有點簡單 - 我嘗試發送一個名爲「X-ANDROID-USER」的cookie,值爲「some name」,所以服務器。 當我得到這個工作,我會改變「一些名字」爲一個獨特的價值。 – Etse 2012-03-20 15:56:47