在Java中發送POST請求,可以使用java.net包中的HttpURLConnection類。以下是一個簡單的示例代碼:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostRequestExample {
public static void main(String[] args) throws IOException {
String url = "http://example.com/api/endpoint";
String requestBody = "param1=value1¶m2=value2";
// 創建URL對象
URL obj = new URL(url);
// 創建HttpURLConnection對象
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
// 設置請求方法為POST
connection.setRequestMethod("POST");
// 啟用輸入輸出流
connection.setDoInput(true);
connection.setDoOutput(true);
// 設置請求頭
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 創建請求體
DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
dataOutputStream.writeBytes(requestBody);
dataOutputStream.flush();
dataOutputStream.close();
// 獲取響應狀態碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應內容
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: " + response.toString());
}
}
在上面的示例中,我們首先創建一個URL對象,然后使用該URL對象創建一個HttpURLConnection對象。接下來,我們設置請求方法為POST,并啟用輸入輸出流。然后,我們設置請求頭,將請求體寫入到輸出流中。之后,我們獲取響應狀態碼和響應內容,并打印出來。