HttpClient授权标头格式无效 [英] HttpClient Authorization Header Invalid Format

查看:488
本文介绍了HttpClient授权标头格式无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用下面的地址和授权值进行 GET 请求时,我没有问题。

When I try to make a GET request with the address and Authorization value below, I have no problems.

地址: http://example.com /xyz.svc/branches/?latitude=0&经度= 0& range = 20000

标头密钥:授权

值:例如; foo

当我用 HttpCLient 尝试时,格式无效授权标头值错误

When I try it with HttpCLient I get format invalid error for the authorization header value

这就是我的尝试

HttpClient client = new HttpClient();

    string latitude = "0";
    string longitude = "0";
    string range = "2000";

    string uri = "/xyz.svc/branches/?latitude=0&longitude=0&range=20000;

    string value = "foo";

    client.BaseAddress = new Uri("http://example.com");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", String.Format("example;{0}", value));

    HttpResponseMessage response = await client.GetAsync(uri);

    var responseJson = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseJson);

我在做什么错了?

推荐答案

通常,授权标头的格式为 {scheme} {token} ,这是它正在尝试使用当前代码进行验证的格式。

Normally that authorization header has a format as {scheme} {token} which is what it is trying to validate with your current code.

p>

可以将某些服务器配置为接受不同的格式。验证标准格式的客户端使用 TryAddWithoutValidation

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", String.Format("example;{0}", value));

根据您的示例,它将具有以下请求标头

which based on your example would have the following request headers

Accept application/json
Authorization example;foo

这篇关于HttpClient授权标头格式无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆