How to get content body from a httpclient call?

前端 未结 2 817
一个人的身影
一个人的身影 2020-12-02 08:06

I\'ve been trying to figure out how to read the contents of a httpclient call, and I can\'t seem to get it. The response status I get is 200, but I can\'t figure out how to

相关标签:
2条回答
  • 2020-12-02 08:26

    The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

    I've rewritten your function and function call, which should fix your issue:

    async Task<string> GetResponseString(string text)
    {
        var httpClient = new HttpClient();
    
        var parameters = new Dictionary<string, string>();
        parameters["text"] = text;
    
        var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
        var contents = await response.Content.ReadAsStringAsync();
    
        return contents;
    }
    

    And your final function call:

    Task<string> result = GetResponseString(text);
    var finalResult = result.Result;
    

    Or even better:

    var finalResult = await GetResponseString(text);
    
    0 讨论(0)
  • 2020-12-02 08:28

    If you are not wanting to use async you can add .Result to force the code to execute synchronously:

    private string GetResponseString(string text)
    {
        var httpClient = new HttpClient();
    
        var parameters = new Dictionary<string, string>();
        parameters["text"] = text;
    
        var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
        var contents = response.Content.ReadAsStringAsync().Result;
    
        return contents;
     }  
    
    0 讨论(0)
提交回复
热议问题