2011-08-20 118 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"));