从httpclient获取响应

时间:2017-12-21 20:40:15

标签: c# httpresponse dotnet-httpclient

我正在尝试将WEB API用于个人学习项目。尝试从服务器获取响应时代码成功,但我无法从响应中获取正文。

我应该得到类似的东西:

{
"start_time": "2017-12-21T11:03:52Z",
"players": 27721,
"server_version": "1223575"
}

但是我得到了这个:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Access-Control-Allow-Credentials: true
  Access-Control-Allow-Headers: Content-Type,Authorization,X-User-Agent
  Access-Control-Allow-Methods: GET,OPTIONS
  Access-Control-Allow-Origin: *
  Access-Control-Expose-Headers: Content-Type,Warning,X-Pages,X-ESI-Error-Limit-Remain,X-ESI-Error-Limit-Reset
  Access-Control-Max-Age: 600
  Strict-Transport-Security: max-age=31536000
  X-Esi-Error-Limit-Remain: 100
  X-Esi-Error-Limit-Reset: 54
  Alt-Svc: clear
  Cache-Control: public
  Date: Thu, 21 Dec 2017 20:38:06 GMT
  Via: 1.1 google
  Content-Length: 80
  Content-Type: application/json
  Expires: Thu, 21 Dec 2017 20:38:34 GMT
  Last-Modified: Thu, 21 Dec 2017 20:38:04 GMT
}

这是我的代码:

static HttpClient client = new HttpClient();

        static void Main(string[] args)
        {
            client.BaseAddress = new Uri("https://esi.tech.ccp.is/latest/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            GetTaskAsync("status/?datasource=tranquility").Wait();
        }

        static async Task GetTaskAsync(String endpoint)
        {
            HttpResponseMessage response = await client.GetAsync(client.BaseAddress + endpoint);         
            Console.WriteLine(response);
        }

2 个答案:

答案 0 :(得分:1)

调用response.Content.ReadAsStringAsync()从回复中读取正文。

答案 1 :(得分:1)

class bitstream {
    std::streambuf* sbuf;
    int             count = 0;
    unsigned char   byte = 0;
public:
    bitstream(std::ostream& out): sbuf(out.rdbuf()) {}
    ~bitstream() {
        if (this->count) {
            this->sbuf->sputc(this->byte);
        }
    }
    bitstream& operator<< (bool b) {
        this->byte = (this->byte << 1) | b;
        if (++this->count == 8) {
            this->sbuf->sputc(this->byte);
            this->count = 0;
        }
        return *this;
    }
};