相关疑难解决方法(0)

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

我想设置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

rest spring resttemplate

173
推荐指数
6
解决办法
30万
查看次数

使用Spring RestTemplate for Android进行经过身份验证的POST请求

我有一个RESTful API,我试图通过Android和RestTemplate连接.所有对API的请求都通过HTTP身份验证进行身份验证,方法是设置HttpEntity的标头,然后使用RestTemplate的exchange()方法.

所有GET请求都以这种方式工作,但我无法弄清楚如何完成经过身份验证的POST请求.postForObjectpostForEntity处理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);
Run Code Online (Sandbox Code Playgroud)

但POST显然无法使用,exchange()因为它从不发送自定义标头,我也看不到如何设置请求体使用exchange().

从RestTemplate进行经过身份验证的POST请求的最简单方法是什么?

java rest spring android resttemplate

58
推荐指数
4
解决办法
18万
查看次数

什么是restTemplate.exchange()方法?

实际上这个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());
}
Run Code Online (Sandbox Code Playgroud)

rest resttemplate

25
推荐指数
3
解决办法
6万
查看次数

标签 统计

rest ×3

resttemplate ×3

spring ×2

android ×1

java ×1