开发者

Sending Cookie info in HttpRequest

I want to call a web service that requires an authentication cookie.

I have the cookie name and value. but I d开发者_如何学Con't know how to inject the cookie in the request.

can you please provide me with a code sample on how to do this.


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.


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);


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜