6

When communicating with http to http://forecast.weather.gov/zipcity.php I need to obtain the URL that is generated from a request.

I have printed out the headers and their values from the http response message but there is no location header. How can I obtain this URL? (I'm using HttpClient)

joepetrakovich
  • 1,344
  • 3
  • 24
  • 42

1 Answers1

12

It should be similar to:

HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpClientParams.setRedirecting(params, false);
HttpGet method = new HttpGet("http://forecast.weather.gov/zipcity.php?inputstring=90210");
HttpResponse resp = client.execute(method);
String location = resp.getLastHeader("Location").getValue();

EDIT: I had to make a couple minor tweaks, but I tested and the above works.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • How were you able to find that out? I am using the .getAllHeaders() function and printing them all out and a location header was not listed. – joepetrakovich Nov 02 '10 at 02:01
  • @Petra, using LiveHttpHeaders and Firebug. I will post an example shortly. Which version of HttpClient are you using? – Matthew Flaschen Nov 02 '10 at 02:02
  • the org.apache.http.client module on Android 2.2 – joepetrakovich Nov 02 '10 at 02:08
  • I downloaded those tools you mentioned and they are awesome! It appears the first response is a redirection to the URL that I am looking for, but when I communicate with the server via HttpClient it seems to be giving me the last http response with a 200 status. Any ideas on obtaining the header info for that very first http response message? – joepetrakovich Nov 02 '10 at 02:16
  • That looks perfect, what does the .setRedirecting() function doing? I could look it up but since you may be active... My first guess would be that it stops all future http communication after that very first redirection response? – joepetrakovich Nov 02 '10 at 02:18
  • @Petra, that's correct. It just tells the library not to follow the redirects on its own. See also [this answer](http://stackoverflow.com/questions/1352949/preventing-httpclient-4-from-following-redirect/1699192#1699192); however, you don't need to create a new params object. – Matthew Flaschen Nov 02 '10 at 02:35