溫馨提示×

java怎么接收response返回內(nèi)容

小億
279
2023-08-30 10:53:26
欄目: 編程語言

在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();
// 設置請求方法
connection.setRequestMethod("GET");
// 獲取響應狀態(tài)碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應內(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();
// 輸出響應內(nèi)容
System.out.println("Response Content: " + response.toString());
// 關閉連接
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);
// 獲取響應狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 獲取響應內(nèi)容
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
// 輸出響應內(nèi)容
System.out.println("Response Content: " + content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 關閉HttpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

以上代碼示例中,分別使用HttpURLConnection和HttpClient發(fā)送GET請求,并接收并輸出響應內(nèi)容。

0