java - 如何将 HttpGet 更改为 HttpPost?
问题描述
我是 Java 新手,我正在缓慢但肯定地学习;对此的任何见解将不胜感激。
我有一些功能性的 HttpGet 代码,我想将其适配到 HttpPost 中,以便我可以打开并发送本地 JSON 文件的内容。我尝试了很多方法,但都失败了,我现在很困惑。
这是我到目前为止转换的 HttpPost 代码。它只有 HttpGet 到 HttpPost 的变化。import org.apache.http.client.methods.HttpPost;
存在。我应该做什么?
@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);
}
}
}
在“get”存在的地方用“post”编辑。
解决方案
您可以尝试这样的事情,在其中使用 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();
}
}
推荐阅读
- pm2 - PM2 生态系统文件 - 将时间戳写入日志
- python - 按多列条件拆分列值的 Pythonic 方法
- swift - 除非保留,否则自定义组合发布器包装类不起作用
- javascript - 在 React 中使用子项和父项留下嵌套的复选框单击
- firebase - Firestore 规则说文档获取功能是错误的
- python - 在 python 中,如何删除不包含特定单词的表格文本格式的行?
- jquery - 我如何提交所有必需的文本框,但一个来自表单?
- c++ - 在 CMake 中导出 3rd 方静态库依赖项的惯用方法是什么?
- php - 为什么 PHP 中的 shmop 这么慢
- python - 顶点吞噬了所有的记忆