代码之家  ›  专栏  ›  技术社区  ›  Ege Bayrak

HttpClient授权标头格式无效

  •  7
  • Ege Bayrak  · 技术社区  · 7 年前

    当我试图 GET 请求地址和授权值如下,我没有问题。

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

    标题键:授权

    值:示例;foo公司

    当我试着 HttpCLient 授权标头值的格式无效错误

    我就是这样尝试的

    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);
    

    我做错了什么?

    1 回复  |  直到 7 年前
        1
  •  16
  •   Nkosi    7 年前

    通常,授权标头的格式为 {scheme} {token} 这就是它试图用当前代码验证的内容。

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

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

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

    Accept application/json
    Authorization example;foo