1

I am trying to write the following code using HttpClient and async, but it's not able return data.

        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.

        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.

5
  • Show us the code containing the Async code. Commented Feb 5, 2017 at 7:37
  • Could you please elaborate, I don't get it. Do you mean you want to see the back-end code? Actually the first code example is working. I like to translate it with HttpClient. Commented Feb 5, 2017 at 7:40
  • How do you call the second version? If you debug and put a breakpoint at the console line, do you hit that breakpoint? Commented Feb 5, 2017 at 8:00
  • I actually found the reason, the cookie is not set properly. It's getting Authorization Failure. RegistrationToken and/or Cookie must be set. Any idea how to set the cookie properly. Commented Feb 5, 2017 at 8:02
  • Look at this SO question. Commented Feb 5, 2017 at 8:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Always explain why an answer will work better than the code in the question. Else you do not educate but just encourage copy/paste behavior.
It's actually getting empty string on line Console.WriteLine(responseData); Do I have to use GetStreamAsync instead of GetAsync?
great. +1 now, but you could make it even clearer by commenting the code line in question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.