在Java中调用POST接口,可以使用Java内置的 HttpURLConnection 类或者 Apache HttpClient 类。下面分别介绍这两种方法:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api/endpoint");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 添加请求头
connection.setRequestProperty("Content-Type", "application/json");
// 启用输出流,并指定请求体的内容
connection.setDoOutput(true);
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(requestBody);
outputStream.flush();
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) {
try {
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建HttpPost对象,并设置URL
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
// 设置请求体的内容
String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
// 发送POST请求
HttpResponse response = httpClient.execute(httpPost);
// 获取响应码
int responseCode = response.getStatusLine().getStatusCode();
// 读取响应内容
HttpEntity responseEntity = response.getEntity();
String responseBody = EntityUtils.toString(responseEntity);
// 打印响应结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + responseBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码示例中,假设要调用的接口为 http://example.com/api/endpoint
,请求体的内容为 {"key1":"value1", "key2":"value2"}
,你需要根据实际情况进行修改。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: Java Lucene最新版本带来了哪些改进