2016-02-01 83 views
0

我想發送一個http post請求並捕獲響應。我寫了下面的代碼。C#在完全加載頁面時捕獲HTTP響應

System.Net.WebRequest req = System.Net.WebRequest.Create(URI); 
    req.Proxy = new System.Net.WebProxy(ProxyString, true); 
    //Add these, as we're doing a POST 
    req.ContentType = "application/x-www-form-urlencoded"; 
    req.Method = "POST"; 
    //We need to count how many bytes we're sending. 
    //Post'ed Faked Forms should be name=value& 
    byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters); 
    req.ContentLength = bytes.Length; 
    System.IO.Stream os = req.GetRequestStream(); 
    os.Write (bytes, 0, bytes.Length); //Push it out there 
    os.Close(); 
    System.Net.WebResponse resp = req.GetResponse(); 
    if (resp== null) return null; 
    System.IO.StreamReader sr = 
     new System.IO.StreamReader(resp.GetResponseStream()); 
    return sr.ReadToEnd().Trim(); 

更新1:

我試圖利用PostAsync方法。還是一樣的結果。

public static async void Req() 
     { 
      using (var client = new HttpClient()) 
      { 
       var values = new Dictionary<string, string> 
    { 
     { "type1", "val1" }, 
     { "type2", "val2" }, 
     { "type3", "val3"} 
    }; 
       var content = new FormUrlEncodedContent(values); 
       var r1 = await client.PostAsync(URL, content); 

       var responseString = await r1.Content.ReadAsStringAsync(); 
       Console.WriteLine(responseString); 
       Console.ReadLine(); 
      } 
     } 

但它只捕獲部分響應。我的頁面需要10-12秒才能加載。如何讓我的腳本等待並捕獲完整的響應?

回答

0

工作代碼。只需將正確的參數傳遞給方法即可。

public static async void Req() 
{ 
    using (var client = new HttpClient()) 
    { 
     var values = new Dictionary<string, string> 
     { 
      { "type1", "val1" }, 
      { "type2", "val2" }, 
      { "type3", "val3"} 
     }; 
      var content = new FormUrlEncodedContent(values); 
      var r1 = await client.PostAsync(URL, content); 

      var responseString = await r1.Content.ReadAsStringAsync(); 
      Console.WriteLine(responseString); 
      Console.ReadLine(); 
     } 
    } 
} 
0

這可能是由於響應編碼爲som其他編碼,然後是StreamReader默認的UTF8編碼。請檢查響應的編碼和改變呼叫從

new System.IO.StreamReader(resp.GetResponseStream()); 

到的StreamReader到

new System.IO.StreamReader(resp.GetResponseStream(), Encoding.ASCII); 

爲ASCII編碼

+0

我發佈的第二種方法是爲我工作。之前我提供了不正確的參數值。異步調用做到了這一點 –

相關問題