Jak ustawić nagłówek "Accept:" na żądaniu Spring RestTemplate?

Chcę ustawić wartość Accept: w żądaniu, które wykonuję używając RestTemplate Springa.

Oto Mój kod do obsługi Spring request

@RequestMapping(
    value= "/uom_matrix_save_or_edit", 
    method = RequestMethod.POST,
    produces="application/json"
)
public @ResponseBody ModelMap uomMatrixSaveOrEdit(
    ModelMap model,
    @RequestParam("parentId") String parentId
){
    model.addAttribute("attributeValues",parentId);
    return model;
}

A oto mój klient Java REST:

public void post(){
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.add("parentId", "parentId");
    String result = rest.postForObject( url, params, String.class) ;
    System.out.println(result);
}

To działa dla mnie; dostaję ciąg JSON od strony serwera.

Moje pytanie brzmi: jak Mogę określić nagłówek Accept: (np. application/json,application/xml, ... ) i metoda żądania (np. GET,POST, ... ) kiedy używam RestTemplate?

Author: ArtB, 2013-10-08

5 answers

Proponuję użyć jednego z exchange metody, które akceptują HttpEntity dla których można również ustawić HttpHeaders. (Możesz również określić metodę HTTP, której chcesz użyć.)

Na przykład,

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

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

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

Wolę to rozwiązanie, ponieważ jest mocno wpisane, tj. exchange oczekuje HttpEntity.

Można jednak również przekazać HttpEntity jako argument request do postForObject.

HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
restTemplate.postForObject(url, entity, String.class); 

Jest to wspomniane w RestTemplate#postForObject Javadoc .

Parametr request może być HttpEntity w celu dodania dodatkowego Nagłówki HTTP do żądania .

 248
Author: Sotirios Delimanolis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 17:41:49

Możesz ustawić interceptor "ClientHttpRequestInterceptor" w RestTemplate, aby uniknąć ustawiania nagłówka za każdym razem, gdy wysyłasz zapytanie.

public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {

        private final String headerName;

        private final String headerValue;

        public HeaderRequestInterceptor(String headerName, String headerValue) {
            this.headerName = headerName;
            this.headerValue = headerValue;
        }

        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            request.getHeaders().set(headerName, headerValue);
            return execution.execute(request, body);
        }
    }

Then

List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);
 86
Author: Ammar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-10 19:34:52

Jeśli, podobnie jak ja, starałeś się znaleźć przykład, który używa nagłówków z podstawowym uwierzytelnieniem i API rest template exchange, to jest to, co w końcu wymyśliłem...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}
 11
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-04 21:26:43

Oto prosta odpowiedź. Mam nadzieję, że to komuś pomoże.

import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


public String post(SomeRequest someRequest) {
    // create a list the headers 
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("username", "user123"));
    interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
    interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
    // initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();
    // set header interceptors here
    restTemplate.setInterceptors(interceptors);
    // post the request. The response should be JSON string
    String response = restTemplate.postForObject(Url, someRequest, String.class);
    return response;
}
 0
Author: Tunde Michael,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-18 14:46:38

Kod: wywołanie rest api za pomocą szablonu

1)

       RestTemplate restTemplate = new RestTemplate();
        // Add the Jackson message converter
        restTemplate.getMessageConverters().add(new 
           MappingJackson2HttpMessageConverter());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Basic XXXXXXXXXXXXXXXX=");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

        restTemplate.getInterceptors().add(new BasicAuthorizationInterceptor(USERID, PWORD));

        String requestJson = getRequetJson(Code, emailAddr, firstName, lastName);
        //
        response = restTemplate.postForObject(URL, requestJson, MYObject.class);

Lub

2)

    RestTemplate restTemplate = new RestTemplate();
    String requestJson = getRequetJson(code, emil, name, lastName);

    //
    HttpHeaders headers = new HttpHeaders();
    String userPass = USERID + ":" + PWORD;
    String authHeaderValue = "Basic " + Base64.getEncoder().encodeToString(userPass.getBytes());
    headers.set(HttpHeaders.AUTHORIZATION, authHeaderValue);
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
    //
    ResponseEntity<MyObject> responseEntity =this.restTemplate.exchange(URI, HttpMethod.POST, request, MyObject.class);

    responseEntity.getBody()

Metoda tworzenia obiektu json

    private String getRequetJson(String Code, String emailAddr, String firstName, String lastName) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.createObjectNode();

        ((ObjectNode) rootNode).put("code", Code);
        ((ObjectNode) rootNode).put("email", emailAdd);
        ((ObjectNode) rootNode).put("firstName", firstname);
        ((ObjectNode) rootNode).put("lastName", lastname);

        String jsonString = null;
        try {
            jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
        } catch (JsonProcessingException e) {

            e.printStackTrace();
        }
        return jsonString;

    }
 0
Author: vaquar khan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 21:12:06