为什么Httpclient总是返回401 Unauthorized错误?

时间:2018-02-05 07:17:09

标签: c# asp.net dotnet-httpclient

我尝试从网络上获取一些数据,但始终会出现 401 Unauthorized 错误。我想这是由我的请求标头设置错误造成的。

我们可以使用 TryAddWithoutValidation 设置接受,ContentType 吗?  如何在HttpClient中设置正确的请求标头?

我尝试将标题设置如下:

public static async Task<ResultInfo> Get(string url, string cookie = null)
        {
            url =$"https://www.zhihu.com/api/v4/questions/46508954/answers?sort_by=default&include=data%5B%2A%5D.is_normal%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Cmark_infos%2Ccreated_time%2Cupdated_time%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cupvoted_followees%3Bdata%5B%2A%5D.author.badge%5B%3F%28type%3Dbest_answerer%29%5D.topics&limit=20&offset=20";

;            var result = new  ResultInfo()
            {
                IsSuccessStatusCode = false
            };

            HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            using (var client = new HttpClient(handler))
            {
                try
                {
                    cookie = "_zap=bb597634-86d0-4636-a516-89e76b4b5335; q_c1=b2e3af8dde034209a6948fcd9fd0e70f|1515131469000|1509512040000; d_c0=\"AJBrsuC5AA2PTqu9qOLgytIZlpXzmzgRgcE=|1516167026\"; _xsrf=ec351d2e-f0b2-4b2e-9eff-a3262a9faf10; capsion_ticket=\"2|1:0|10:1516261057|14:capsion_ticket|44:NzU1ZGRjYTA3Y2U3NGVjZWE4MWIzMzllNjA1NjMxZGQ=|b73bb13fe6a623db85478f5eb46ed51906674b89f29e4ef1a067fce6dcd90f54\"; z_c0=\"2|1:0|10:1516261068|4:z_c0|92:Mi4xMzMwVEFBQUFBQUFBa0d1eTRMa0FEU1lBQUFCZ0FsVk56SnhOV3dETFF5VGlla1ZDUllwcUVMRVhMWk4wV1duOVJn|f2fcc1750b966a19dd202ddc2eb42dca9dc9f573421bc3a8675a072e603ca897\"; __utma=51854390.1320208938.1517560249.1517560249.1517560249.1; __utmb=51854390.0.10.1517560249; __utmc=51854390; __utmz=51854390.1517560249.1.1.utmcsr=zhihu.com|utmccn=(referral)|utmcmd=referral|utmcct=/question/38824940; __utmv=51854390.100-1|2=registration_date=20130816=1^3=entry_date=20130816=1";
                    var replace = cookie.Replace("\"", "");

                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "*/*");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("ContentType", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("UserAgent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Cookie", replace);
                    client.DefaultRequestHeaders.TryAddWithoutValidation("accept-encoding", "gzip/deflate");
                    //client.DefaultRequestHeaders.TryAddWithoutValidation("accept-language", "en-US,en;q=0.9");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("AllowAutoRedirect","false");

                    if (!string.IsNullOrEmpty(url))
                    {
                        var data = await client.GetAsync(url);
                        if (data.IsSuccessStatusCode)
                        {
                            var content = await data.Content.ReadAsStringAsync();   
                            result.IsSuccessStatusCode = true;
                            result.Data = await data.Content.ReadAsStringAsync();
                        }
                        else
                        {
                            result.Message = data.StatusCode.ToString();
                        }
                    }
                }
                catch (Exception e)
                {
                    result.Message = e.Message;
                    throw;
                }
            }
            return result;
        }

0 个答案:

没有答案