2015-01-02 104 views
1

我有一個簡單的情況。沒有得到正確的頭響應代碼與HttpUrlConnection

給定一個URL,服務器頭響應代碼將HTTP 200

現在我當服務器先用HTTP 302(實測),回答另一個URL嘗試它,然後重定向並用頭回應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包含標題關鍵:「位置」,雖然不如預期,connection.getheaderFields()不包含它。

回答

相關問題