2020-07-04

Restful client call HTTP headers - Accept header parameter example

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending on the context where the request is done: when fetching a CSS stylesheet a different value is set for the request than when fetching an image, video or a script.

Syntax

Accept: <MIME_type>/<MIME_subtype>
Accept: <MIME_type>/*
Accept: */*

Directives

<MIME_type>/<MIME_subtype>
A single, precise MIME type, like text/html.

<MIME_type>/*
A MIME type, but without any subtype. image/* will match image/png, image/svg, image/gif and any other image types.

*/*
Any MIME type

;q= (q-factor weighting)
Any value used is placed in an order of preference expressed using relative quality value called the weight.


Examples

Accept: text/html

Accept: image/*

// General default
Accept: */*

// Default for navigation requests
Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8

Add headers on restful call using jersey client api:


Client client = Client.create();
WebResource webResource = client.resource("uri");

MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request

appKey = "Bearer " + appKey; // appKey is unique number

//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
    .header("Accept", "application/json;charset=UTF-8")
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);

Spring - Add headers on restful call : 

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

HttpEntity<String> entity = new HttpEntity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

See all available mime types  - https://www.iana.org/assignments/media-types/media-types.xhtml

No comments:

Post a Comment