How to use HttpWebRequest (.NET) asynchronously?

后端 未结 8 1588
天涯浪人
天涯浪人 2020-11-22 13:56

How can I use HttpWebRequest (.NET, C#) asynchronously?

8条回答
  •  北海茫月
    2020-11-22 14:22

    public static async Task GetBytesAsync(string url) {
        var request = (HttpWebRequest)WebRequest.Create(url);
        using (var response = await request.GetResponseAsync())
        using (var content = new MemoryStream())
        using (var responseStream = response.GetResponseStream()) {
            await responseStream.CopyToAsync(content);
            return content.ToArray();
        }
    }
    
    public static async Task GetStringAsync(string url) {
        var bytes = await GetBytesAsync(url);
        return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
    }
    

提交回复
热议问题