简体   繁体   English

C# HttpClient 用法

[英]C# HttpClient usage

I am trying to write the following code using HttpClient and async, but it's not able return data.我正在尝试使用 HttpClient 和异步编写以下代码,但它无法返回数据。

        WebRequest request = WebRequest.Create("some_url");
        request.Headers.Add("cookie", "some_cookie");

        Stream objStream = request.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);
        string sLine = "";
        int i = 0;
        while (sLine != null)
        {
            i++;
            sLine = objReader.ReadLine();
            if (sLine != null)
                Console.WriteLine(sLine);
        }

Here is what I tried.这是我尝试过的。

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("cookie", "some_cookie");
            using (var response = await client.GetAsync("some_url"))
            {
                string responseData = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseData);
            }
        }

Any help will be appreciated.任何帮助将不胜感激。

Edit : Here is the code that works for me using HttpClient.编辑:这是使用 HttpClient 对我有用的代码。

        var baseAddress = new Uri(baseUrl);
        using (var handler = new HttpClientHandler { UseCookies = false })
        using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
        {
            var requestMessage = new HttpRequestMessage(HttpMethod.Get, queryString);
            requestMessage.Headers.Add("cookie", cookie);
            var response = client.SendAsync(requestMessage);
            response.Wait();
            var content = response.Result.Content.ReadAsStringAsync();
            content.Wait();
            Console.WriteLine(content.Result);
        }

Thanks for all the help.感谢所有的帮助。

You are doing the async and await, but you are not waiting for response data to be returned or reached so the following snippet will do the job :您正在执行异步和等待,但您不是在等待返回或到达响应数据,因此以下代码段将完成这项工作:

Try this code :试试这个代码:

  static async Task<string> HttpGetResponse()
    {
        WebRequest request = WebRequest.Create("some_url");
        request.Headers.Add("cookie", "some_cookie");
        string responseData;
        Stream objStream = request.GetResponse().GetResponseStream();
        StreamReader objReader = new StreamReader(objStream);
        string sLine = "";
        int i = 0;
        while (sLine != null)
        {
            i++;
            sLine = objReader.ReadLine();
            if (sLine != null)
                Console.WriteLine(sLine);
        }

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("cookie", "some_cookie");
            using (var response = await client.GetAsync("some_url"))
            {
                responseData = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseData);
            }
        }

        return responseData;
    }

in main call it like this :在主要调用它是这样的:

static void Main(string[] args)
   {
       Task<string> t = HttpGetResponse();


      //Do alot of work

       t.Wait();
       string response = t.Result;

       Console.WriteLine(response);
   }

Hope this was useful.希望这是有用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM