关于网址重定向的问题:
在网络链接的时候,int responseCode = conn.getResponseCode(),当responseCode大于300而且小于399的时候,地址重定向。如何获取重定向地址。
String location = conn.getHeaderField("Location");从http中返回的头部中的属性Location
值,若为空,可以手动赋值(在某些设备上,可以会出现为空的情况)。可以用调试的办法,将返回的头部中的属性值全部打印出来,
//通过循环,获取http的头部中的各项字段,将其打印。
private void PrintHeadFieldMsg(HttpConnection c)
{
try
{
int i = 0;
String s = null;
s = c.getHeaderField(i);
while (s != null)
{
i++;
s = c.getHeaderField(i);
}
}
catch (Exception e)
{
Util.form("PrintHeadFieldMsg exception!");
}
}
若location不为空,直接将其作为参数,重新建立链接conn = (HttpConnection) Connector.open(location, Connector.READ);
整个过程如下:
while (responseCode >= 300 && responseCode <= 399) //http code Redirection
{
String location = conn.getHeaderField("Location");
//做一个冗余处理,在某些设备中通过conn.getHeaderField("Location")方法,返回的值为空
if (location == null)
{
PrintHeadFieldMsg(conn);
location = conn.getHeaderField("location");
if (location == null)
{
location = url2;
}
}
location = url2;
//必须关闭先前建立的链接,便于后面重新建立链接
if (conn != null)
{
conn.close();
}
Util.form((new Date()).toString());
conn = (HttpConnection) Connector.open(location, Connector.READ);
responseCode = conn.getResponseCode();
}