【问题标题】:Add custom rest header in api is not working在 api 中添加自定义休息标头不起作用
【发布时间】:2020-10-03 16:37:49
【问题描述】:

我需要通过我自己的 api 调用第三方 api。第三方 api 需要自定义标头进行身份验证,我不希望将其暴露给客户端。所以我所做的是添加自定义标头并在我的 api 中调用第三方 api。但它不起作用。

@GetMapping(value = "/downloadCompletedDocument/{id}", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<byte[]> download(@PathVariable("id") String id, @RequestHeader Map header)
{
    HttpHeaders headers = new HttpHeaders();
    headers.set("userloginname", "testUser");
    headers.set("organizationkey", "testOrganization");
    HttpEntity<String> requestEntity = new HttpEntity<>(headers);

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<byte[]> responseObj = restTemplate
            .exchange(url + id, HttpMethod.GET, requestEntity,
                    byte[].class);
    return responseObj;
}

但是当我通过传递标头使用该工具时,它可以成功运行。这是我不明白的。

PS:我试过过滤器,但结果相同。

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException
{

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(req);
    Enumeration<String> a = req.getHeaderNames();
    mutableRequest.putHeader("userloginname", "testUser");
    mutableRequest.putHeader("organizationkey", "testOrganization");
    Enumeration<String> b = mutableRequest.getHeaderNames();
    chain.doFilter(mutableRequest, response);
}

【问题讨论】:

  • 请提供更多细节以供我理解,1.您是否可以通过邮递员(或您使用的其他客户端工具)调用第三方api。如果是,请在您的代码中放置一个 logger 并打印标题详细信息和 url - 确保邮递员标题 + url 组合等同于它在控制台中打印的内容。 2. 你能从邮递员那里调用你本地的api吗?
  • @Govind 是的。我可以通过rest客户端工具调用第三方api和我的api。问题是当我通过工具传递身份验证标头时,我从第三方 api 获得了我想要的 pdf。但是当我从工具中删除标头并在我的 api 中“硬编码”时,我得到了响应状态 401。我相信当我调用第三方 api 时“硬编码”标头不起作用。
  • 我相信您能够调用您的本地 api 并且 401 正在向第三方 url 抛出 .. 话虽如此,您能否尝试在代码中添加以下内容类型,看看是否如此作品? headers.setContentType(MediaType.APPLICATION_JSON);
  • 很遗憾,它不起作用。
  • 抱歉,内容类型应为 APPLICATION_OCTET_STREAM 或 APPLICATION_PDF。试试下面的,看看它是否也有效。 RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter()); HttpHeaders 标头 = 新的 HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));

标签: spring rest http-headers


【解决方案1】:

我通过将第三方 api url 从 http 更改为 https 解决了这个问题。不知道为什么这不会影响其余客户端工具。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多