我想设置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;
}
这是我的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);
}
这适合我; 我从服务器端获得了一个JSON字符串.
我的问题是:当我使用RestTemplate时,如何指定Accept:标题(例如application/json,application/xml...)和请求方法(例如,...)?GETPOST
我有一个RESTful API,我试图通过Android和RestTemplate连接.所有对API的请求都通过HTTP身份验证进行身份验证,方法是设置HttpEntity的标头,然后使用RestTemplate的exchange()方法.
所有GET请求都以这种方式工作,但我无法弄清楚如何完成经过身份验证的POST请求.postForObject并postForEntity处理POST,但没有简单的方法来设置身份验证标头.
因此对于GET来说,这很有用:
HttpAuthentication httpAuthentication = new HttpBasicAuthentication("username", "password");
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(httpAuthentication);
HttpEntity<?> httpEntity = new HttpEntity<Object>(requestHeaders);
MyModel[] models = restTemplate.exchange("/api/url", HttpMethod.GET, httpEntity, MyModel[].class);
但POST显然无法使用,exchange()因为它从不发送自定义标头,我也看不到如何设置请求体使用exchange().
从RestTemplate进行经过身份验证的POST请求的最简单方法是什么?
实际上这个restTemplate.exchange()方法做了什么?
@RequestMapping(value = "/getphoto", method = RequestMethod.GET)
public void getPhoto(@RequestParam("id") Long id, HttpServletResponse response) {
    logger.debug("Retrieve photo with id: " + id);
    // Prepare acceptable media type
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.IMAGE_JPEG);
    // Prepare header
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(acceptableMediaTypes);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    // Send the request as GET
    ResponseEntity<byte[]> result = 
        restTemplate.exchange("http://localhost:7070/spring-rest-provider/krams/person/{id}", 
                              HttpMethod.GET, entity, byte[].class, id);
    // Display the image
    Writer.write(response, result.getBody());
}