java - 如何在 java 中执行这样的 Post 请求?
问题描述
我有一个像这样的 Curl 发布请求程序。我怎样才能在java中完成这项工作?
curl -X POST \
-H "api_key: xxxxxxxxxxxxx" \
-H "speed: 0" \
-H "voice: male" \
-H "prosody: 1" \
-H "Cache-Control: no-cache" \
-d 'This is the text to transfer' \
"http://somewhere.com"
解决方案
我使用Apache创建一个可运行的POST
请求示例
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
...
public static void main(String[] args) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://reqres.in/api/register");
// Simple data
httppost.setEntity(
new StringEntity("{\"email\":\"eve.holt@reqres.in\",\"password\":\"pistol\"}",ContentType.create("application/json", StandardCharsets.UTF_8)));
// Simple Header
httppost.setHeader("cache-control", "no-cache");
// Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Status: " + response.getStatusLine().toString());
if (entity != null) {
try (InputStream instream = entity.getContent()) {
System.out.println("response: " + IOUtils.toString(instream, StandardCharsets.UTF_8));
}
}
}
来自的回应System.out.println()
状态:HTTP/1.1 200 OK
响应:{"id":4,"token":"QpwL5tke4Pnpja7X4"}
推荐阅读
- python - XMLParser skips attributes while parsing XML Schema file
- google-sheets - 如何像使用 Excel 公式一样将数据输入表格?
- java - 如何从 SQS 触发器调用涉及 spring cloud feign 的 lambda 函数
- android - 当我拍照时,某些 Android 设备上的应用程序崩溃
- python - 使用 datefinder 提取日期时间字符串
- python - 如何使用 pandas 跨列替换时间戳
- python - Docker - REST 不提供 python 应用程序
- c++ - 联合中的 Flatbuffers 结构不起作用(C++)
- javascript - 按药丸/按钮过滤,而不是使用选择 - 角度
- sql - 根据第三列值在 bigquery 中选择两个不同的列