如何在Spring RestTemplate请求上设置"Accept:"标头?

eda*_*lij 173 rest spring resttemplate

我想设置Accept:我使用Spring的请求中的值RestTemplate.

这是我的Spring请求处理代码

@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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的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);
}
Run Code Online (Sandbox Code Playgroud)

这适合我; 我从服务器端获得了一个JSON字符串.

我的问题是:当我使用RestTemplate时,如何指定Accept:标题(例如application/json,application/xml...)和请求方法(例如,...)?GETPOST

Sot*_*lis 313

我建议使用其中一种exchange方法来接受HttpEntity你也可以设置的方法HttpHeaders.(您还可以指定要使用的HTTP方法.)

例如,

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);
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种解决方案,因为它是强类型的,即.exchange期待一个HttpEntity.

但是,您也可以将其HttpEntity作为request参数传递给postForObject.

HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class); 
Run Code Online (Sandbox Code Playgroud)

这在RestTemplate#postForObjectJavadoc中提到过.

request参数可以是HttpEntity为了向请求添加其他HTTP标头.

  • 如果未设置接受标头,则默认情况下在restTemplate.exchange()中设置MediaType.APPLICATION_JSON. (8认同)

Amm*_*mar 117

您可以在RestTemplate中设置拦截器"ClientHttpRequestInterceptor",以避免每次发送请求时都设置标头.

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后

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

RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);
Run Code Online (Sandbox Code Playgroud)

  • 你为什么需要HttpRequestWrapper? (6认同)
  • 出于某种原因,HttpHeaderInterceptor 仅在 spring-boot-devtools 中。所以我们还是要自己实现ClientHttpRequestInterceptor。我认为它应该被移到 spring-web 中。 (6认同)
  • 我更好地接受你的方法,因为它允许以一种非常弹簧的方式使用Spring,使用特殊方法`postForObject`等,而不是`exchange`.谢谢! (5认同)
  • 将默认标头添加到设置为其余模板的ClientHttpRequestFactory而不是添加拦截器是否更好?PS,您应该在单独的问题中添加答案,因为这涉及默认标题。只好寻找一段时间才能到达这里! (2认同)

Dav*_*ave 18

如果像我一样,你很难找到一个使用带有基本身份验证和其他模板交换API的头文件的例子,那么这就是我最终解决的问题......

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());
    }
}
Run Code Online (Sandbox Code Playgroud)


GKi*_*lin 11

无需创建的简短解决方案HttpHeaders

RequestEntity<Void> request = RequestEntity.post(URI.create(url))
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON)
                // any other headers
                .header("PRIVATE-TOKEN", "token")
                .build();

ResponseEntity<String> response = restTemplate.exchange(request, String.class);
return response.getBody();
Run Code Online (Sandbox Code Playgroud)

更新:但如果特定的标头HttpHeaders变得简单:

RequestEntity.post(URI.create(AMOCRM_URL + url))
            .contentType(MediaType.APPLICATION_JSON)
            .headers(
                    new HttpHeaders() {{
                        setBearerAuth(getAccessToken());
                    }})
            .body(...)
Run Code Online (Sandbox Code Playgroud)


vaq*_*han 9

代码:使用模板调用rest api

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);
Run Code Online (Sandbox Code Playgroud)

要么

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()
Run Code Online (Sandbox Code Playgroud)

创建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;

    }
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一个简单的答案。希望它可以帮助某人。

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 您的代码将使用 Spring Devtools 作为生产依赖项(通过导入 org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor)... (14认同)