HttpResponse code 302

2019-05-11 15:33发布

问题:

I am using simulator BB 8900. I am trying to connect to url and get response code 302.What does it mean? Here is my code snippet:

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
.....
connection = (HttpConnection)Connector.open(url);
responseCode = connection.getResponseCode();

回答1:

An HTTP 302 is a 'temporary redirect'. You need to handle it.

As per the standard, if you get a 302 response, the response will contain a 'Location' header field with the redirect:

Client request:
GET /index.html HTTP/1.1
Host: www.example.com

Server response:
HTTP/1.1 302 Found
Location: http://www.redirected-address.example.com/

You need to extract the new URL from the response. (Use getHeaderField("Location") to do this). Then execute the same method on the new URL you got.

Two other points:

  1. Since this is a 'temporary' redirect, you cannot store this new URL. You should keep using the old one, and if it returns a 302, then use whatever URL is in 'Location'.

  2. If you are not executing a GET or HEAD, you shouldn't do the redirect automatically. Instead ask for user intervention. The RFC requires this.