共計 1959 個字符,預(yù)計需要花費 5 分鐘才能閱讀完成。
在 Java 中可以使用 HttpURLConnection 或者 HttpClient 來接收 response 返回內(nèi)容。
使用 HttpURLConnection 的示例代碼如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientExample {public static void main(String[] args) {
try {
// 創(chuàng)建 URL 對象
URL url = new URL("http://example.com");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設(shè)置請求方法
connection.setRequestMethod("GET");
// 獲取響應(yīng)狀態(tài)碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code:" + responseCode);
// 讀取響應(yīng)內(nèi)容
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {response.append(line);
}
reader.close();
// 輸出響應(yīng)內(nèi)容
System.out.println("Response Content:" + response.toString());
// 關(guān)閉連接
connection.disconnect();} catch (IOException e) {e.printStackTrace();
}
}
}
使用 HttpClient 的示例代碼如下:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {public static void main(String[] args) {CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 創(chuàng)建 HttpGet 對象
HttpGet httpGet = new HttpGet("http://example.com");
// 執(zhí)行請求
HttpResponse response = httpClient.execute(httpGet);
// 獲取響應(yīng)狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code:" + statusCode);
// 獲取響應(yīng)內(nèi)容
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
// 輸出響應(yīng)內(nèi)容
System.out.println("Response Content:" + content);
} catch (IOException e) {e.printStackTrace();
} finally {
try {
// 關(guān)閉 HttpClient
httpClient.close();} catch (IOException e) {e.printStackTrace();
}
}
}
}
以上代碼示例中,分別使用 HttpURLConnection 和 HttpClient 發(fā)送 GET 請求,并接收并輸出響應(yīng)內(nèi)容。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完