C#:HttpClient响应时出错

时间:2016-10-06 07:30:26

标签: c# .net console-application httpclient

我在C#console app中使用HttpClient进行HTTP get请求。我没有通过一个获取请求获得预期的响应。

获取请求就像 http://example.com/xyz/SearchProduct?productNo=11210&1d6rstc9xc=5jyi27htzk

我得到了一些模糊的回答,但是当我做同样的事情时,请小提琴手给出了预期的回应。

如何从httpClient.GetAsync(url)获得预期的响应?

代码是: -

            var httpClient = new HttpClient();
            var url = "http://example.com/xyz/SearchProduct?productNo=11210&1d6rstc9xc=5jyi27htzk";

            HttpResponseMessage response1 = await httpClient.GetAsync(url);

            if (response1.IsSuccessStatusCode)
            {

                HttpContent stream = response1.Content;
                Task<string> data = stream.ReadAsStringAsync();

            }

2 个答案:

答案 0 :(得分:0)

你应该这样读取字符串:

string result = await stream.ReadAsStringAsync();

而不是:

Task<string> data = stream.ReadAsStringAsync();

Here full code exampleanother example

答案 1 :(得分:0)

这是使用 async / await 方法的完整方法。

   private static async Task<string> GetRequestContentAsString(string url)
    {
        var data = string.Empty;

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                var stream = response.Content;
                data = await stream.ReadAsStringAsync();
            }
        }

        return data;
    }

此方法以这种方式调用:

var content = await GetRequestContentAsString("http://www.bing.com");