Robin Green
Robin Green

Reputation: 33063

How to handle cookies like a web browser using App Engine url fetch service?

I have seen many questions about using cookies with url fetch on App Engine, but many people doing it incorrectly, and no confirmed-as-working solutions on Java App Engine.

All I want to do is:

  1. Make one request
  2. Get the cookies from that request.
  3. Make a second request, with those cookies.

How hard can it be??

This is easy to do on the dev server, because the dev server copies cookies across requests automatically - and indeed it's impossible to stop it doing this. But the real App Engine urlfetch service does not do this.

Upvotes: 1

Views: 539

Answers (1)

Robin Green
Robin Green

Reputation: 33063

Use

new HTTPRequest(url, HTTPMethod.GET, fetchOptions.doNotFollowRedirects())

to create the request object.

The doNotFollowRedirects() is essential for some reason. I don't understand why.

Then get the set-cookie headers from the response (ones whose names equalsIgnoreCase("Set-Cookie")) and create a corresponding Cookie header - trimming off everything after the semicolon in each Set-Cookie header, if there is one, and then concatenating all the cookies together with ; as a separator.

This doesn't correctly deal with expiration etc., but this should be enough for most purposes.

Upvotes: 2

Related Questions