2016-07-22 24 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); 
    }