91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

java怎么獲取response返回內容

小億
393
2023-10-09 19:55:43
欄目: 編程語言

在Java中,可以使用HTTPURLConnection或HttpClient來獲取HTTP響應的內容。

使用HTTPURLConnection的示例代碼如下:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法為GET
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
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.toString());
} else {
System.out.println("HTTP request failed. Response Code: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用HttpClient的示例代碼如下:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpGet httpGet = new HttpGet("http://example.com");
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
System.out.println(responseString);
} else {
System.out.println("HTTP request failed. Response Code: " + statusCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
}
}

這些代碼示例使用HTTP GET請求來獲取響應的內容,并將其打印到控制臺。你可以根據實際需要進行修改和適配。

0
江山市| 东丰县| 保康县| 比如县| 邛崃市| 吕梁市| 独山县| 肇州县| 惠水县| 华阴市| 扶余县| 贺兰县| 浮梁县| 德庆县| 正蓝旗| 泾源县| 灵丘县| 蛟河市| 诏安县| 曲阜市| 洪雅县| 富宁县| 城固县| 上思县| 平昌县| 广水市| 绥棱县| 忻州市| 庄浪县| 镇坪县| 和硕县| 利川市| 宁河县| 临潭县| 灵宝市| 苏尼特右旗| 崇文区| 鹤壁市| 永寿县| 山东省| 通山县|