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.

Ulka
  • 71
  • 2
  • 9
  • Show us the code containing the Async code. – Jeroen Heier Feb 05 '17 at 07: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. – Ulka Feb 05 '17 at 07:40
  • How do you call the second version? If you debug and put a breakpoint at the console line, do you hit that breakpoint? – Jeroen Heier Feb 05 '17 at 08: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. – Ulka Feb 05 '17 at 08:02
  • Look at [this SO](http://stackoverflow.com/questions/12373738/how-do-i-set-a-cookie-on-httpclients-httprequestmessage) question. – Jeroen Heier Feb 05 '17 at 08:28

1 Answers1

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.

Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
  • 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. – jgauffin Feb 05 '17 at 07:50
  • It's actually getting empty string on line Console.WriteLine(responseData); Do I have to use GetStreamAsync instead of GetAsync? – Ulka Feb 05 '17 at 07:52
  • great. +1 now, but you could make it even clearer by commenting the code line in question. – jgauffin Feb 05 '17 at 11:49