简体   繁体   English

通过 Jersey 客户端调用 REST api 时添加多个标头

[英]Adding multiple headers while calling REST api via Jersey clients

I am trying to add multiple header.我正在尝试添加多个标题。 But failed miserably so far.但至今都惨败。 I had tried lots of code tweaking but failed.我尝试了很多代码调整但失败了。 Can someone help me fix the code or at least tell me what's wrong ?有人可以帮我修复代码或至少告诉我出了什么问题吗?

Header mapping code:头映射代码:

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

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

actual calling code:实际调用代码:

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

UPDATE更新

if in second snippet I use below code instead of setting headers in loop, it works fine.如果在第二个片段中我使用下面的代码而不是在循环中设置标题,它工作正常。 That's really weird.这真的很奇怪。

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

I think the issue here is, type of MAP that you are trying to access.我认为这里的问题是,您尝试访问的 MAP 类型。

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

The WebSource builder accepts header(String,Object). WebSource 构建器接受 header(String,Object)。 So Try with changing the map type.所以尝试改变地图类型。

Basic auth is like: Authorization = "Authorization" ":" credentials基本身份验证类似于: Authorization = "Authorization" ":" 凭据

an example一个例子

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

_headers.put("Authorization", authString );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM