簡體   English   中英

使用apache httpclient如何為http請求設置cookie

[英]Using apache httpclient how to set cookie for http request

我想在發送http請求之前設置abc = 123 cookie。

在回復中,我希望將相同的cookie發回。 但是在響應中我得到abc = 890,其中值由目標服務器設置。

        DefaultHttpClient httpclient = new DefaultHttpClient();
    CookieStore cookieStore = httpclient.getCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("abc", "123");

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://abc.net/restofurl");

    cookieStore.addCookie(cookie);
    httpclient.setCookieStore(cookieStore);

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);

    // Examine the response status
    log.info("Http request response is: " + response.getStatusLine());

    List<Cookie> cookies = cookieStore.getCookies();

    for (int i=0; i<cookies.size();i++) {

        if (cookies.get(i).getName().toString().equals("abc")) {
            log.info("cookie is: " + cookies.get(0).getValue().toString());
            }
    }

謝謝

添加后它起作用了

cookie.setDomain(".xyz.net");
cookie.setPath("/");

是通過改變來解決問題的

log.info("cookie is: " + cookies.get(0).getValue().toString());

log.info("cookie is: " + cookies.get(i).getValue().toString());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM