Read text from response

后端 未结 7 1110
野趣味
野趣味 2020-12-04 23:48
HttpWebRequest request = WebRequest.Create(\"http://google.com\") as HttpWebRequest;  

request.Accept = \"application/xrds+xml\";  
HttpWebResponse response = (Http         


        
7条回答
  •  一整个雨季
    2020-12-05 00:05

    The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.

    To perform an HTTP GET and read the response text, do the following.

    .NET 1.1 ‒ 4.0

    public static string GetResponseText(string address)
    {
        var request = (HttpWebRequest)WebRequest.Create(address);
    
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            var encoding = Encoding.GetEncoding(response.CharacterSet);
    
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream, encoding))
                return reader.ReadToEnd();
        }
    }
    

    .NET 4.5

    private static readonly HttpClient httpClient = new HttpClient();
    
    public static async Task GetResponseText(string address)
    {
        return await httpClient.GetStringAsync(address);
    }
    

提交回复
热议问题