Cookie management with Java URLConnection

一世执手 提交于 2019-12-02 04:31:20

You need to maintain your cookie context external to each call and provide the same cookie store it on subsequent GETs and POSTs. This is the same for both the Java implementation and Apache's implementation.

In my experience, Apache's HTTP components is better than the built in Java implementation. I spent a large amount of time trying to write a utility using Java's implementation, my largest problem was timeouts. Bad web servers would hang causing the connection to hang indefinitely. After switching to Apache the timeouts were tuneable and we didn't have any more hung threads.


I'll give an example using Apache.

Create the CookieStore instance in your parent method:

CookieStore cookieStore = new BasicCookieStore();

Then in your GET or POST implementations pass in the CookieStore instance and use it when you build the HttpClient:

public void sendGet(String url, CookieStore cookieStore) throws Exception {
    ...
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    HttpGet request = new HttpGet(uri);  // or HttpPost...
    request.addHeader("User-Agent", USER_AGENT);
    HttpResponse response = client.execute(request);

    BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    ...
}

Android has extended java.net.HttpURLConnection and recommends using this, so I'll also give an outline for that as well.

HttpURLConnection and HttpsURLConnection automatically and transparently uses the CookieManager set in CookieHandler. CookieHandler is VM-wide so must be setup only once. If you create a new CookieManager for each request, as you did in your code, it will wipe out any cookies set in previous requests.

You do not need to create an instance of HttpCookie yourself. When HttpURLConnection receives a cookie from the server the CookieManager will receive the cookie and store it. Future requests to the same server will automatically send the previously set cookies.

So, move this code to your application setup so it happens only once:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!