401未经授权,并使用C#HttpClient库

时间:2019-07-09 18:26:57

标签: c# httpwebrequest dotnet-httpclient

我正在尝试将c#中的代码从HttpWebRequest升级到HttpClient。

我无法通过HttpClient验证第三方服务,并且邮递员或httpwebrequest库没有看到此问题

我尝试过邮递员。

Postman Console窗口参考:

GET / api / v2 / geocodes / a973-5a1c5d435990 内容类型:application / json 授权:JWT ey ----- iJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTYzMDEwOTg4LCJqdGkiOiIwNWM3 缓存控制:无缓存 邮递员令牌:8d46fa25-698c-477d-a86e-bbc546ad0470 用户代理:PostmanRuntime / 7.6.0 接受: / 接受编码:gzip,放气 引荐来源:http://api.concept.quincus.com/api/v2/geocodes/3d0a4758-611e-448f-a973-5a1c5d435990

工作代码:

var httpWebRequest = (HttpWebRequest)WebRequest.Create(
                        quincusGeoCodeDataRequest.endpoint);

                    httpWebRequest.ContentType = "application/json";
                    httpWebRequest.Headers.Add("AUTHORIZATION", "JWT " + quincusGeoCodeDataRequest.quincusTokenData.token);
                    httpWebRequest.Method = "GET";
                    httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                    string response;

                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        response = streamReader.ReadToEnd();
                        streamReader.Close();
                    }

我正在尝试使用HttpClient库实现相同的代码

var response = string.Empty;
            using (var client = new HttpClient())
            {
                HttpRequestMessage request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri("http://sample.com/3d0a4758"),

                };

                request.Headers.Authorization = new AuthenticationHeaderValue("JWT","eyJ0eXAiOiJKV1QiLC");

                HttpResponseMessage result = await client.SendAsync(request);
                if (result.IsSuccessStatusCode)
                {
                    response = result.StatusCode.ToString();
                }
            }
            return response;

它总是返回未经授权的401。我不知道哪里出问题了?

我想看看如何为上述httpwebrequest代码段实现httpclient

1 个答案:

答案 0 :(得分:0)

使用Bearer更改JWT并将AUTHORIZATION更改为Authorization