[英]How can I change HttpGet into HttpPost?
I am new to java and I am learning slowly but surely;我是 Java 新手,我的学习速度很慢但很确定; any insight to this would be greatly appreciated.
对此的任何见解将不胜感激。
I have some functional HttpGet code that I want to adapt into HttpPost so that I can open and send the contents of a local JSON file.我有一些功能性的 HttpGet 代码,我想将它们改编成 HttpPost,以便我可以打开和发送本地 JSON 文件的内容。 I've attempted numerous methods but they've all failed and I have now confused myself.
我尝试了很多方法,但都失败了,我现在很困惑。
This is the HttpPost code I have converted so far.这是我到目前为止转换的 HttpPost 代码。 It has only the change of HttpGet to HttpPost.
它只有 HttpGet 到 HttpPost 的变化。
import org.apache.http.client.methods.HttpPost;
is present.存在。 What should I be doing?
我该怎么办?
@Component
public class ServiceConnector {
private final HttpClient client;
public ServiceConnector() {
client = HttpClientBuilder.create().build();
}
public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
HttpPost request = new HttpPost(url);
request.addHeader("Accept", acceptHeader);
if (bearerToken.isPresent()) {
request.addHeader("Authorization", "Bearer " + bearerToken.get());
}
try {
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 401) {
throw new UnauthorizedException();
}
return EntityUtils.toString(response.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Edited with "post" where "get" existed.使用存在“get”的“post”进行编辑。
You can try something like this, where you prepare the post request with the JSON and then execute it:您可以尝试这样的操作,您可以使用 JSON 准备发布请求,然后执行它:
@Component
public class ServiceConnector {
private final HttpClient client;
public ServiceConnector() {
client = HttpClientBuilder.create().build();
}
public String post(String url, String acceptHeader, Optional<String> bearerToken) throws UnauthorizedException {
try {
HttpPost request = new HttpPost(url);
request.addHeader("Accept", acceptHeader);
if (bearerToken.isPresent()) {
request.addHeader("Authorization", "Bearer " + bearerToken.get());
}
StringEntity params =new StringEntity("details {\"name\":\"myname\",\"age\":\"20\"} ");
// You could open, read, and convert the file content into a json-string (use GSON lib here)
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = client.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
client.getConnectionManager().shutdown();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.