2016-07-22 63 views
0

我試圖用頭找重定向URL,所以我用Google搜索了一圈,發現了幾個例子:獲取使用鏈接重定向後的HTTPClient

Header[] arr = httpResponse.getHeaders("Location"); 
for (Header head : arr){ 
    String whatever = arr.getValue(); 
} 

HttpPost request1 = new HttpPost("https://hrlink.healthnet.com/"); 
HttpResponse response1 = httpclient.execute(request1); 

// expect a 302 response. 
if (response1.getStatusLine().getStatusCode() == 302) { 
    String redirectURL = response1.getFirstHeader("Location").getValue(); 

    // no auto-redirecting at client side, need manual send the request. 
    HttpGet request2 = new HttpGet(redirectURL); 
    HttpResponse response2 = httpclient.execute(request2); 

    ... ... 
} 

他們得到從頭部的「位置」,但是我不能從我的版本拉出HttpResponseMessage的「位置」,我試着在這裏和那裏移動東西,但它不包含接受參數的方法,我怎麼能夠得到使用httpClient的重定向網址?

var client = new HttpClient(); 

var pairs = new List<KeyValuePair<string, string>> 
{ 
    new KeyValuePair<string, string>("username", "---"), 
    new KeyValuePair<string, string>("password", "---") 
}; 

var content = new FormUrlEncodedContent(pairs); 

var response = client.PostAsync(uri, content).Result; 


HttpHeaders headerlist = response.Headers; 

foreach (var header in headerlist) 
{ 
    //Red line on header("Location") 
    label1.Text += header("Location") + "\n"; 
} 
+0

設置AllowAutoRedirect爲false:https://msdn.microsoft.com/en-us/library/system .net.httpwebrequest.allowautoredirect(v = vs.110).aspx然後你可以找到「位置」 – 2016-07-22 09:03:23

+0

@x ...我如何從HttpWebResponse獲取「位置」? –

+1

HttpWebResponse.Headers:https://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.headers(v=vs.110).aspx – 2016-07-22 09:28:46

回答

0

只是爲了測試,與www.google.com可以測試重定向:

var request = (HttpWebRequest) WebRequest.Create("http://www.google.com"); 
    request.AllowAutoRedirect = false; 
    using (var response = (HttpWebResponse) request.GetResponse()) 
    { 
    string location = response.Headers["Location"]; 
    Console.WriteLine(location); 
    }