feign icon indicating copy to clipboard operation
feign copied to clipboard

A bug of header adding and getting in OpenFeign RequestInterceptor

Open HaojunRen opened this issue 2 years ago • 7 comments

Refer to the following issue at Spring Cloud community

https://github.com/spring-cloud/spring-cloud-openfeign/issues/760

HaojunRen avatar Mar 21 '23 11:03 HaojunRen

Hi!

Please try to put keys to doublequoters, it works:

  @Test
  public void headerWithJSONValue() {
    RequestTemplate template = new RequestTemplate()
        .header("key", "{\"x\":1.0,\"y\":1.1}");

    assertThat(template.headers()).hasSize(1);
    assertThat(template.headers().keySet()).containsExactly("key");
    assertThat(template.headers().get("key")).containsExactly("{\"x\":1.0,\"y\":1.1}");
  }

vitalijr2 avatar Mar 22 '23 15:03 vitalijr2

It does not make sense, that means i should add double-quoters to every header value with json format one by one?

HaojunRen avatar Apr 14 '23 09:04 HaojunRen

This is JSON's rule: string are wrapped double quotes, both in keys and values.

And as far as I guess this rule is used to avoid processing of header value, see Request Headers Expansion that uses curly brackets like JSON does.

vitalijr2 avatar Apr 14 '23 13:04 vitalijr2

It does not make sense, that means i should add double-quoters to every header value with json format one by one?

As @radio-rogal has stated, Feign supports expression based headers. This means you can use URI templates in your header values and have them resolved at execution time. The incompatibility you are seeing is related to the use of JSON as a header value, which conflicts with the URI Template specification where dynamic expressions are wrapped in braces {}.

If you chose to use Feign and require JSON based header values, you will need to quote them as discussed.

kdavisk6 avatar May 24 '23 14:05 kdavisk6

1699345955608

Can you add a switch here to enable parsing JSON data?

yangyang122 avatar Nov 07 '23 08:11 yangyang122

I try : String data="{\"x\":1.0,\"y\":2.0}"; RequestTemplate rq = requestTemplate.header("v", data); Map<String, Collection<String>> headers = rq.headers(); headers.forEach((key, values) -> { System.out.println(key+"--"+values); }); result : v--[{"x":1.0,"y"}], but it's not the expected value.

yangyang122 avatar Nov 07 '23 09:11 yangyang122

Hi!

Please try to put keys to doublequoters, it works:

  @Test
  public void headerWithJSONValue() {
    RequestTemplate template = new RequestTemplate()
        .header("key", "{\"x\":1.0,\"y\":1.1}");

    assertThat(template.headers()).hasSize(1);
    assertThat(template.headers().keySet()).containsExactly("key");
    assertThat(template.headers().get("key")).containsExactly("{\"x\":1.0,\"y\":1.1}");
  }

It doesn't work in version: spring-cloud-starter-openfeign: 3.1.4 feign-core: 11.8

hyfsy avatar Dec 14 '23 02:12 hyfsy