gpt4 book ai didi

java - 使用 HttpClient 和 HttpMethod 放置包含内容的请求

转载 作者:行者123 更新时间:2023-12-02 05:52:14 24 4
gpt4 key购买 nike

我使用 HttpClient 和 HttpMethod 来触发我的 REST 服务,但如果我想为 put 方法提供一些内容,它不起作用。服务在网络服务器上触发,但内容为空。

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;
}

最佳答案

这就是我所做的,不仅可以在正文中发布带有 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;

关于java - 使用 HttpClient 和 HttpMethod 放置包含内容的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com