温馨提示×

java怎么接收response返回内容

小亿
292
2023-08-30 10:53:26
栏目: 编程语言

在Java中可以使用HttpURLConnection或者HttpClient来接收response返回内容。

使用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 {
// 创建URL对象
URL url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应内容
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();
// 输出响应内容
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 {
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://example.com");
// 执行请求
HttpResponse response = httpClient.execute(httpGet);
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 获取响应内容
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
// 输出响应内容
System.out.println("Response Content: " + content);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭HttpClient
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

以上代码示例中,分别使用HttpURLConnection和HttpClient发送GET请求,并接收并输出响应内容。

0