Skip to content

Sending and Receiving Headers

Lahiru Sahan Jayasinghe edited this page Dec 25, 2013 · 9 revisions

A request or response contains headers which are used to relay meta-information and control the communication between the client and sever. Such a header could be a predefined standard or a custom header prefixed with X-.


####1. Sending Request Headers

A request header is identified using the @Header annotation with the header name placed on a parameter of type CharSequence. The header value can be provided as an argument when the request is being invoked.

@Deserialize(JSON)
@Endpoint("https://api.github.com")
public interface GitHubEndpoint {

    @GET("/users/{user}/repos")
    List<Repo> getRepos(@Header("Accept") String header);
}

...

List<Repo> repos = gitHubEndpoint.getRepos("application/vnd.github.v3");

request-headers: "Accept: application/vnd.github.v3"

To skip sending a defined request header, simply pass null or "".

gitHubEndpoint.getRepos(null);   /* or */   gitHubEndpoint.getRepos("");

request-headers: <none>


####2. Defining Static Request Headers

Certain requests might require a header whose value will remain constant across all invocations. Such headers are considered to be static and can be defined using @Headers and @Headers.Header.

@Deserialize(JSON)
@Endpoint("https://api.github.com")
public interface GitHubEndpoint {

    @GET("/users/{user}/repos")
    @Headers({@Headers.Header(name = "User-Agent", value = "MyGitHubApp-v1"),
              @Headers.Header(name = "Accept", value = "application/vnd.github.v3")})
    List<Repo> getRepos(@PathParam("user") String user);
}

request-headers: "User-Agent: MyGitHubApp-v1, Accept: application/vnd.github.v3"


####3. Extracting Response Headers

Response headers are identified the same way request headers are using an @Header annotation. However, the parameter type on which the annotation is applied should be an instance of StringBuilder.

@Deserialize(JSON)
@Endpoint("https://api.github.com")
public interface GitHubEndpoint {

    @GET("/users/{user}/repos")
    List<Repo> getRepos(@PathParam("user") String user, 
                        @Header("X-RateLimit-Remaining") StringBuilder responseHeader);
}

...

StringBuilder responseHeader = new StringBuilder();

List<Repo> repos = gitHubEndpoint.getRepos(responseHeader);

String rateLimitRemaining = responseHeader.toString();

response-headers: "X-RateLimit-Remaining: 4950"
rateLimitRemaining: 4950