在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"}
,你需要根據實際情況進行修改。