【问题标题】:How does feign obtain header data for the requested interfacefeign如何获取请求接口的header数据
【发布时间】:2019-12-04 12:51:21
【问题描述】:

我正在请求一个带有feign 的接口,并且需要获取该接口的Headers 值。

我之前用feign为请求的接口headers传递参数,将token传给headers:

@RequestMapping(method = RequestMethod.GET, value = "/api/get-store-list")
List<Store> getStoreList(@RequestHeader("Authorization") String Authorization);

但是,这个接口把数据量放在headers的x-total-count中,所以我还是需要得到x-total-count的值。 如何获取x-total-count 的值。

【问题讨论】:

  • 我不太了解细节。您所说的“这个界面放置了数据量 [...]”是什么意思? X-Total-Count 标头是对 /api/get-store-listresource 的调用的答案的一部分吗?
  • 页面 storePage = storeRepo.findAll(pageable); response.addHeader("X-Total-Count", storePage.getTotalElements() + "");这将列表的数量存储在“x-total-count”中
  • 现在您想编写一个与 Feign 一起使用的接口,该接口将读取该资源并提取其 X-Total-Count 标头,以便您提前知道需要多少分页获取?
  • 是的,最终目的是得到X-Total-Count的值

标签: spring-cloud-feign feign


【解决方案1】:

Feign 在Response 对象中有标题,这可以是返回值:

public interface Swapi {
    @RequestLine("GET /people/{id}/")
    Response personResponse(@Param("id") int person);
}

现在您可以在结果上调用headers()。当然,这会让你的身体像一根绳子一样,这并不漂亮。让我们尝试一些更像 Feign 的东西。


@Data
public class Person {
    String name;
    int height;
    int mass;
}

public interface Swapi {
    @RequestLine("GET /people/{id}/")
    Person person(@Param("id") int person);
}

现在标题再次被隐藏,但它们仍然可供解码器使用,这是我将插入的地方:

@RequiredArgsConstructor
public class HeaderReadingDecoder implements Decoder {

    private final Decoder wrappedDecoder;

    @Override
    public Object decode(Response response, Type type) throws IOException {
        var server = response.headers().getOrDefault("server",
            List.of("")).iterator().next();
        System.out.println("server = " + server);
        var etag = response.headers().getOrDefault("etag",
            List.of("")).iterator().next();
        System.out.println("etag = " + etag);
        return wrappedDecoder.decode(response, type);
    }
}

当然,System.out 是邪恶的,但我真的不知道你想用那个标头值做什么。由你决定。现在您可以将其用于:

Swapi swapi = Feign.builder()
    .decoder(new HeaderReadingDecoder(new JacksonDecoder()))
    .target(Swapi.class, "https://swapi.co/api");
Person person = swapi.person(2);
System.out.println("person = " + person);

你会得到:

server = cloudflare
etag = "3a58f420395ff0deed943e331d3bf74b"
person = Person(name=C-3PO, height=167, mass=75)

【讨论】:

  • 好吧,@kangwenLiu,如果它对您有足够的帮助,您可能希望接受这个答案作为正确答案。
  • “感谢您的反馈!声望低于 15 人的投票会被记录下来,但不会改变公开显示的帖子得分。” !!! :(
  • 我明白了。自从我的第一天以来已经很长时间了,但我真的认为会有那个灰色的刻度线可以变成绿色。以后也许吧。
  • 现在好了。我犯了一个错误
猜你喜欢
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 2019-03-03
  • 2021-07-06
  • 2018-10-30
  • 1970-01-01
  • 2012-11-24
  • 1970-01-01
相关资源
最近更新 更多