Sending Cookie info in HttpRequest

前端 未结 5 1497
抹茶落季
抹茶落季 2020-12-10 20:11

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.

相关标签:
5条回答
  • 2020-12-10 20:31

    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();
    
    0 讨论(0)
  • 2020-12-10 20:34

    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.

    0 讨论(0)
  • 2020-12-10 20:43
    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 讨论(0)
  • 2020-12-10 20:47

    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"));
    
    0 讨论(0)
  • 2020-12-10 20:48

    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);
    
    0 讨论(0)
提交回复
热议问题