2

I want to pass a header to each POST request in a retrofit api . Since i have lots of methods hear, i can't copy/paste the header information for every method.

public interface ApiInterface {
    String[] header = {"Accept:application/json",
                       "apiKey:12345",
                       "Content-Type:application/json"};

    @Headers(header)
    @POST("signup?")
    Call<SignupResponse> createUser(@Body SignupData signupData);

    @Headers(header)
    @POST("another")
    ....
}

The header variable in @HEADER creates this error:

Attribute must be constant

How can i solve the problem?

Ehsan Toghian
  • 548
  • 1
  • 6
  • 26
  • Is there any problem if you remove, `Accept` and `Content-Type` part? Just try with `@Header()` which requires `String` type not `String[]` use ("apiKey:12345"). And also why don't you try Retrofit's [HttpInterceptor](https://stackoverflow.com/a/35024248/5180017)? – Shashanth Nov 10 '19 at 15:27
  • 1
    The **SOLUTION** was the link which @Shashanth recommended. I should use the HttpClient interceptor to add headers to retrofit obj. – Ehsan Toghian Nov 11 '19 at 07:44

2 Answers2

2

Try this

@Headers({"Accept:application/json",
            "apiKey:12345",
            "Content-Type:application/json"})
@POST("signup?")
    Call<SignupResponse> createUser(@Body SignupData signupData);
Rajnish suryavanshi
  • 3,168
  • 2
  • 17
  • 23
1

Use:

@Headers({"Accept:application/json",
         "apiKey:12345",
         "Content-Type:application/json"})
@POST("another")

See the "Header Manipulation" section of the Retrofit documentation.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491