一,原始方式
使用JAVA.NET包中的HttpURLConnection類。以下是一個(gè)簡(jiǎn)單的示例代碼,用于發(fā)送GET請(qǐng)求并獲取響應(yīng):
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 {
// 創(chuàng)建URL對(duì)象
URL url = new URL("http://example.com");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設(shè)置請(qǐng)求方法
connection.setRequestMethod("GET");
// 獲取響應(yīng)代碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應(yīng)內(nèi)容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.Append(line);
}
reader.close();
// 打印響應(yīng)內(nèi)容
System.out.println("Response: " + response.toString());
// 斷開連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代碼用于發(fā)送GET請(qǐng)求,您可以更改請(qǐng)求方法和URL以適應(yīng)您的實(shí)際需求。請(qǐng)注意,HTTP請(qǐng)求是不安全的,建議在實(shí)際使用中使用HTTPS來確保數(shù)據(jù)的安全傳輸。
二,使用Apache HttpClient庫
使用Apache HttpClient庫。請(qǐng)確保您的項(xiàng)目中包含了相關(guān)的依賴
示例代碼:
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 {
// 創(chuàng)建HttpClient對(duì)象
HttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建HttpPost對(duì)象,并設(shè)置URL
HttpPost httpPost = new HttpPost("https://example.com");
// 設(shè)置請(qǐng)求頭
httpPost.setHeader("Content-Type", "application/json");
// 設(shè)置請(qǐng)求體
String requestBody = "{"key1":"value1","key2":"value2"}";
StringEntity requestEntity = new StringEntity(requestBody);
httpPost.setEntity(requestEntity);
// 發(fā)送POST請(qǐng)求
HttpResponse response = httpClient.execute(httpPost);
// 獲取響應(yīng)代碼
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應(yīng)內(nèi)容
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();
// 打印響應(yīng)內(nèi)容
System.out.println("Response: " + responseContent.toString());
// 斷開連接
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述示例代碼中,我們使用了Apache HttpClient庫來發(fā)送HTTPS的POST請(qǐng)求。您可以根據(jù)實(shí)際需求修改請(qǐng)求的URL、請(qǐng)求頭、請(qǐng)求體等部分。請(qǐng)確保您的項(xiàng)目中包含了Apache HttpClient庫的依賴。






