错误:InvalidOperationException HttpResponseMessage响应

时间:2017-05-13 14:31:04

标签: c#

我遇到了HttpResponsemessage流程的问题,一切都适用于发送请求,但在阅读响应时我遇到了错误

  

InvalidOperationException:ContentType中提供的字符集无效。

using (var handler = new HttpClientHandler())
{
    if (handler.SupportsAutomaticDecompression)
    {
        handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    }
    using (var client = new HttpClient(handler) { BaseAddress = new Uri(BaseAddress) })
    {
        Dictionary<string, string> dico = new Dictionary<string, string>();
        dico.Add("username", _username);
        dico.Add("password", _password);

        HttpResponseMessage response = client.PostAsync("/auth", new FormUrlEncodedContent(dico)).Result;
        var tokResult = response.Content.ReadAsStringAsync().Result;
        var tokObj = JsonConvert.DeserializeObject<AuthResult>(tokResult);
        string token = tokObj.Token;
        return token;
    }
}

响应的标头值:

  

{StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StreamContent,标题:{连接:keep-alive服务器:cloudflare-nginx传输编码:chunked CF-RAY: 35e6bfcc8f3c3c77-CDG T411-node:webus1 Set-Cookie:__ cffidid = db2de200ea64f72bef261054785e1047c1494690372; expires = Sun,13-May-18 15:46:12 GMT;路径= /;域= .t411.al; HttpOnly日期:2017年5月13日星期六15:46:12 GMT X-Powered-By:PHP / 5.5.38-4 + deb.sury.org~xenial + 1 Content-Type:text / html;字符集=窗口1252}}

1 个答案:

答案 0 :(得分:0)

我找到的解决方案是:

 var request = (HttpWebRequest)WebRequest.Create(BaseAddress + "/auth");

        var postData = "username=" + _username ;
        postData += "&password=" + _password;
        var data = Encoding.ASCII.GetBytes(postData);


        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";

        using (var stream = request.GetRequestStreamAsync().Result)
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)request.GetResponseAsync().Result;

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        var tokObj = JsonConvert.DeserializeObject<AuthResult>(responseString);

        string token = tokObj.Token;
        return token;