Programing

httpclient 호출에서 콘텐츠 본문을 가져 오는 방법은 무엇입니까?

lottogame 2020. 9. 20. 10:31
반응형

httpclient 호출에서 콘텐츠 본문을 가져 오는 방법은 무엇입니까?


나는 httpclient 호출의 내용을 읽는 방법을 알아 내려고 노력했지만 그것을 얻을 수없는 것 같습니다. 내가 얻는 응답 상태는 200이지만 반환되는 실제 Json에 도달하는 방법을 알 수 없습니다.

다음은 내 코드입니다.

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;
    Task<HttpResponseMessage> response = 
        httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));

    return await response.Result.Content.ReadAsStringAsync();
}

그리고 나는 그것을 메소드에서 호출하고 있습니다.

Task<string> result =  GetResponseString(text);

그리고 이것은 내가 얻는 것입니다

response Id = 89, Status = RanToCompletion, Method = "{null}", Result = "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:\r\n{\r\n Connection: keep-alive\r\n Date: Mon, 27 Oct 2014 21:56:43 GMT\r\n ETag: \"5a266b16b9dccea99d3e76bf8c1253e0\"\r\n Server: nginx/0.7.65\r\n Content-Length: 125\r\n Content-Type: application/json\r\n}" System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>

업데이트 : 이것은 아래 Nathan의 응답에 따른 현재 코드입니다.

    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;
    }

그리고 나는 이것을이 방법에서 부른다 ....

 string AnalyzeSingle(string text)
    {
        try
        {
            Task<string> result = GetResponseString(text);
            var model = JsonConvert.DeserializeObject<SentimentJsonModel>(result.Result);

            if (Convert.ToInt16(model.pos) == 1)
            {
                _numRetries = 0;
                return "positive";
            }

            if (Convert.ToInt16(model.neg) == 1)
            {
                _numRetries = 0;
                return "negative";
            }

            if (Convert.ToInt16(model.mid) == 1)
            {
                _numRetries = 0;
                return "neutral";
            }

            return "";
        }
        catch (Exception e)
        {
            if (_numRetries > 3)
            {
                LogThis(string.Format("Exception caught [{0}] .... skipping", e.Message));
                _numRetries = 0;
                return "";
            }
            _numRetries++;
            return AnalyzeSingle(text);
        }
    }

그리고 그것은 영원히 계속 실행되고, 한 var model = JsonConvert.DeserializeObject<SentimentJsonModel>(result.Result);줄을 치고, 다른 중단 점에서 멈추지 않고 계속 진행됩니다.

실행을 일시 중지하면

Id = Cannot evaluate expression because the code of the current method is optimized., Status = Cannot evaluate expression because the code of the current method is optimized., Method = Cannot evaluate expression because the code of the current method is optimized., Result = Cannot evaluate expression because the code of the current method is optimized.

.. I Continue execution, but it just runs forever. Not sure what the problem is


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);

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;
 }  

참고URL : https://stackoverflow.com/questions/26597665/how-to-get-content-body-from-a-httpclient-call

반응형