我使用HttpClient和HttpMethod来触发我的REST服务,但是如果我想给put方法一些内容,那是行不通的。该服务在Webservcer上触发,但内容为空。
public boolean putter(String url, String entity) {
httpClient = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("user", "pw");
httpClient.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
uri = "http://localhost:59189/v1/";
HttpMethod method = new PutMethod(uri + url);
try {
HttpPut putRequest = new HttpPut(uri + url);
putRequest.setHeader("Content-Type", "application/json");
if (entity != null) {
StringEntity ent = new StringEntity(entity);
if (entityContentType != null) {
ent.setContentType(entityContentType.toString());
}
putRequest.setEntity(ent);
}
httpClient.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
return false;
}
答案 0 :(得分:0)
这是我不仅要在正文中发布带有json的帖子,而且还要通过修改后的正文来答复请求
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<String>(json.toString(), headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responsee =null;
try{
responsee = restTemplate.postForEntity( "http://localhost:59189/v1/", request , String.class );
}catch (HttpClientErrorException e){
return ResponseEntity.status(401)
.body("usuario não encontrado");
}
使用的图书馆
导入org.springframework.http。;
导入org.springframework.web.bind.annotation。;
导入org.springframework.web.client.HttpClientErrorException;
导入org.springframework.web.client.RestTemplate;
导入javax.servlet.http.HttpServletResponse;