2011-08-20 33 views
4

我想調用一個需要身份驗證Cookie的Web服務。在HttpRequest中發送Cookie信息

我有cookie名稱和值。但我不知道在請求中注入cookie。

可否請您提供一個關於如何做到這一點的代碼示例。

回答

0
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

如果您使用(Http)UrlConnection作爲請求,那麼您可以使用CookieManager來處理cookie。 Here是一篇關於如何使用它的文章。

0

沒有辦法將一個cookie添加到HttpRequest,但您可以設置標題或參數。

餅乾添加到HttpServletResponse的是這樣的:

HttpServletResponse response; //initialized or passed in 
Cookie cookie = new Cookie("myname", "myvalue"); 
response.addCookie(cookie); 
2

今天,我解決了使用HttpURLConnection類與此相同的問題:

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

您可以使用droidQuery處理請求:

$.ajax(new AjaxOptions().url("http://www.example.com") 
         .type("POST") 
         .dataType("json") 
         .data("data to post") 
         .cookies($.map($.entry("key", "value")))); 

droidQuery也有認證內置使用標準HTTP認證方式:

$.ajax(new AjaxOptions().url("http://www.example.com") 
         .type("POST") 
         .dataType("json") 
         .data("data to post") 
         .username("myusername") 
         .password("myPassword"));