【发布时间】:2015-02-28 19:15:54
【问题描述】:
我的情况很简单。
给定一个 URL,服务器标头响应代码将为 HTTP 200。
现在我正在尝试使用另一个 URL,其中服务器首先响应 HTTP 302(找到)然后重定向并响应标头 HTTP 200 代码。
因此,在第二种情况下,为什么connection.getResponseCode() 不返回 HTTP 302 而是直接返回 HTTP 200。我实际上有兴趣检查初始 HTTP 302 响应中的标头响应。
这是简化的 HttpUrlConnection 代码(几乎是许多开源实现的抄本)。
private int responseCode;
private Map<String, List<String>> headerFields;
public String getString(String url)
{
String response = null;
try
{
URL mUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
connection.setRequestMethod("GET");
responseCode = connection.getResponseCode();
headerFields = connection.getHeaderFields();
/* boilerplate buffered reader stuffs for getting stream + StringBuilder etc etc.*/
}
finally
{
connection.disconnect();
}
return response;
}
额外信息:HTTP 302 包含标题键:'location',但正如预期的那样,connection.getheaderFields() 不包含它。
【问题讨论】:
标签: java android http httpurlconnection