I want to call a web service that requires an authentication cookie.
I have the cookie name and value. but I don\'t know how to inject the cookie in the request.
Today, i solve the same problem using HttpUrlConnection with this:
CookieManager cookieManager = CookieManager.getInstance();
String cookieString = cookieManager.getCookie(SystemConstants.URL_COOKIE);
URL url = new URL(urlToServer);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Cookie", cookieString);
connection.connect();
OutputStream out = connection.getOutputStream();
out.write(data.getBytes());
out.flush();
out.close();
If you are using (Http)UrlConnection for the request, then you can use CookieManager to handle cookies. Here is an article on how to use it.
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpGet = new HttpGet("http://www.domain.com/");
HttpResponse response = httpClient.execute(httpGet, localContext);
You can use droidQuery to handle the request:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.data("data to post")
.cookies($.map($.entry("key", "value"))));
droidQuery also has authentication built in using the standard HTTP authentication approach:
$.ajax(new AjaxOptions().url("http://www.example.com")
.type("POST")
.dataType("json")
.data("data to post")
.username("myusername")
.password("myPassword"));
There is no method for adding a cookie to an HttpRequest
, but you can set a header or parameter.
Cookies are added to the HttpServletResponse like this:
HttpServletResponse response; //initialized or passed in
Cookie cookie = new Cookie("myname", "myvalue");
response.addCookie(cookie);