Ale*_*dre 14 java rest spring resttemplate
我在使用Spring restTemplate时遇到了问题.
现在我正在发送一个PUT请求一个宁静的服务,而宁静的服务让我回复了重要的信息作为回应.
问题是restTemplate.put是一个void方法而不是一个字符串,所以我看不到那个响应.
根据一些答案,我改变了我的方法,现在我正在使用restTemplate.exchange,这是我的方法:
public String confirmAppointment(String clientMail, String appId)
{
    String myJsonString = doLogin();
    Response r = new Gson().fromJson(myJsonString, Response.class);
    // MultiValueMap<String, String> map;
    // map = new LinkedMultiValueMap<String, String>();
    // JSONObject json;
    // json = new JSONObject();
    // json.put("status","1");
    // map.add("data",json.toString());
    String url = getApiUrl() + "company/" + getCompanyId() + "/appointment/" + appId + "?session_token=" + r.data.session_token;
    String jsonp = "{\"data\":[{\"status\":\"1\"}]}";
    RestTemplate rest = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json");
    headers.add("Accept", "*/*");
    HttpEntity<String> requestEntity = new HttpEntity<String>(jsonp, headers);
    ResponseEntity<String> responseEntity = 
            rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);
    return responseEntity.getBody().toString();
}
使用上面的方法,我收到400 Bad Request
我知道我的参数,网址等等,都很好,因为我可以像这样做一个restTemplate.put请求:
try {
    restTemplate.put(getApiUrl() + "company/" + getCompanyId() + "/appointment/" + appId + "?session_token=" + r.data.session_token, map);
} catch(RestClientException j)
{
    return j.toString();
}
问题(就像我之前说的那样)是上面的try/catch没有返回任何响应,但它给了我200响应.
所以现在我问,哪有什么不对?
dan*_*ter 24
以下是检查PUT响应的方法.您必须使用template.exchange(...)来完全控制/检查请求/响应.
    String url = "http://localhost:9000/identities/{id}";       
    Long id = 2l;
    String requestBody = "{\"status\":\"testStatus2\"}";
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON); 
    HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers); 
    ResponseEntity<String> response = template.exchange(url, HttpMethod.PUT, entity, String.class, id);
    // check the response, e.g. Location header,  Status, and body
    response.getHeaders().getLocation();
    response.getStatusCode();
    String responseBody = response.getBody();
您可以使用标题向您的客户简要发送一些内容.否则您也可以使用以下方法.
restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, ...)
您将能够通过它返回响应实体.
| 归档时间: | 
 | 
| 查看次数: | 41747 次 | 
| 最近记录: |