【问题标题】:Adding multiple headers while calling REST api via Jersey clients通过 Jersey 客户端调用 REST api 时添加多个标头
【发布时间】:2017-02-01 09:01:35
【问题描述】:

我正在尝试添加多个标题。但到目前为止失败得很惨。我尝试了很多代码调整但失败了。有人可以帮我修复代码或至少告诉我出了什么问题吗?

标头映射代码:

    Map<String, String> headers = new HashMap<String, String>();

    headers.put("authorization", authToken);
    headers.put("API-Version", apiVersion);
    headers.put("Content-Type", MediaType.APPLICATION_JSON);

实际调用代码:

    String serviceUrl = serviceHostUrl;
    Client client = Client.create();
    WebResource webResource = client.resource(serviceUrl).path(path);

    WebResource.Builder builder = webResource.getRequestBuilder();
    if(headers != null && !headers.isEmpty()) {
        for(Map.Entry<String, String> entry : headers.entrySet()) {
            builder.header(entry.getKey(), entry.getValue());
        }
    }

    ClientResponse response = builder.post(ClientResponse.class, input);

更新

如果在第二个 sn-p 中我使用下面的代码而不是在循环中设置标题,它可以正常工作。这真的很奇怪。

    builder.header("authorization", "Basic SDFSFSDFSDFSDFSDFSDFSDF");
    builder.header("API-Version", "5.2");
    builder.header("Content-Type", MediaType.APPLICATION_JSON);

【问题讨论】:

  • “但到目前为止失败得很惨。”。您遇到了什么问题/错误?
  • 我正在尝试向 POST 调用添加多个标头,但是在调用时附加一个标头(始终是地图中的最后一个标头)而不是三个。
  • 代码看起来不错。在 headers 的 for 循环中添加一些日志记录语句,以查看在 headers 中添加的条目是否仍然保持。
  • 只添加循环中的最后一个条目。
  • @ManinGreen 你的问题得到了正确的答案吗?请分享!

标签: java rest jersey http-headers jersey-client


【解决方案1】:

我认为这里的问题是,您尝试访问的 MAP 类型。

Map<String, Object> headers = new HashMap<String, Object>();

WebSource 构建器接受 header(String,Object)。所以尝试更改地图类型。

【讨论】:

    【解决方案2】:

    基本身份验证类似于:Authorization = "Authorization" ":" credentials

    一个例子

    byte[] loginBytes = ("1" + ":" + "1").getBytes();
    StringBuilder authString = new StringBuilder().append("Basic ")
                    .append(Base64.encodeToString(loginBytes, Base64.NO_WRAP));
    
    _headers.put("Authorization", authString );
    

    【讨论】:

    • 我的问题与授权无关。请重新阅读问题。
    • 这不能回答问题。
    猜你喜欢
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2015-05-17
    • 2017-02-12
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多