一,原始方式
使用JAVA.NET包中的HttpURLConnection類。以下是一個簡單的示例代碼,用于發送GET請求并獲取響應:
javaCopy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequestExample {
public static void mAIn(String[] args) {
try {
// 創建URL對象
URL url = new URL("http://example.com");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法
connection.setRequestMethod("GET");
// 獲取響應代碼
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());
// 斷開連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代碼用于發送GET請求,您可以更改請求方法和URL以適應您的實際需求。請注意,HTTP請求是不安全的,建議在實際使用中使用HTTPS來確保數據的安全傳輸。
二,使用Apache HttpClient庫
使用Apache HttpClient庫。請確保您的項目中包含了相關的依賴
示例代碼:
javaCopy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
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.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpsPostRequestExample {
public static void main(String[] args) {
try {
// 創建HttpClient對象
HttpClient httpClient = HttpClients.createDefault();
// 創建HttpPost對象,并設置URL
HttpPost httpPost = new HttpPost("https://example.com");
// 設置請求頭
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();
System.out.println("Response Code: " + responseCode);
// 讀取響應內容
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder responseContent = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
responseContent.append(line);
}
reader.close();
// 打印響應內容
System.out.println("Response: " + responseContent.toString());
// 斷開連接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代碼中,我們使用了Apache HttpClient庫來發送HTTPS的POST請求。您可以根據實際需求修改請求的URL、請求頭、請求體等部分。請確保您的項目中包含了Apache HttpClient庫的依賴。