HttpRequestMessage.Content 带有无效和不可读的字符

Posted

技术标签:

【中文标题】HttpRequestMessage.Content 带有无效和不可读的字符【英文标题】:HttpRequestMessage.Content comes with invalid and unreadable characters 【发布时间】:2021-03-01 04:03:41 【问题描述】:

当我从 HttpRequestMessage.Contenc 获得返回时,它就好像它被加密了一样。有人已经经历过类似的事情

        var client2 = new HttpClient();

        client2.DefaultRequestHeaders.Accept.Clear();
        client2.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

        var httpRequestMessage = new HttpRequestMessage
        
            Method = HttpMethod.Post,
            RequestUri = uri,
            Headers = 
             HttpRequestHeader.Authorization.ToString(), $"Bearer resulttoken.access_token" ,
            ,
            Content = new StringContent(dic.ToString())
        ;

        //posting the data here to the endpoint and capturing the request.
        var response_teste = client2.SendAsync(httpRequestMessage).Result;
        var Result_final = await response_teste.Content.ReadAsStringAsync();

结果/

"�\b\0\0\0\0\0\0\0�M�0@\u1ad0���c��p�\a(��6A��aa�w�� _F��ld/�RG!(��y^��E�Y�18mԩb������\fk%����ԭ��BsCH��זU�U6Z��z���� );�]4�a\n�+�~�4*�`����0�1N-tR��/����\0\0\0"

【问题讨论】:

Revolvido HttpClient client2 = new HttpClient(new HttpClientHandler() AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate ); 【参考方案1】:

除了直接使用response.Content.ReadAsStringAsync(),你可以使用response.Content.ReadAsBufferAsync()来检查它是否有效:

var buffer = await response.Content.ReadAsBufferAsync();
var byteArray = buffer.ToArray();
var responseString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);

这对我来说是可行的,我想使用 UTF8 应该可以解决大部分问题。

【讨论】:

以上是关于HttpRequestMessage.Content 带有无效和不可读的字符的主要内容,如果未能解决你的问题,请参考以下文章