I am currently working on a mobile app that is going to communicate with a RESTfull server over the HTTP-protocol. For this I have made a working code and got the communication working.
For the server to identify users I wanted to use cookies (some kind of sessions cookie). So I have started out with the two following helper-methods to create a HttpClient and a context (that includes my 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;
}
I then connect to the server using the following (read function). That basically takes the Client and Conext generate by the last two helper methods and do a normal GET-request.
// Connects to the restfull server and returns the return value (get request)
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
As you can see, this does not include any cookies. Thats why I wonder, why arent the cookie made in "getHttpContext" sent in the request?