久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

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

136次閱讀
沒有評論

共計 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ì)的資源集合!

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-12-21發(fā)表,共計1959字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 屏南县| 瓦房店市| 蒙阴县| 得荣县| 天等县| 古浪县| 福清市| 谷城县| 黄梅县| 抚州市| 洪湖市| 邵东县| 梧州市| 泰宁县| 徐汇区| 稷山县| 阿图什市| 镇沅| 剑河县| 南漳县| 赤城县| 浮山县| 郁南县| 集安市| 云浮市| 买车| 徐州市| 田东县| 南岸区| 南京市| 滨海县| 聊城市| 英德市| 张家口市| 青岛市| 黄山市| 壤塘县| 蓝田县| 五指山市| 合山市| 嫩江县|