云服务器免费试用

java怎么接收response返回内容

服务器知识 0 917

在Java中可以使用HttpURLConnection或者HttpClient来接收response返回内容。
使用HttpURLConnection的示例代码如下:
```java
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的示例代码如下:
```java
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请求,并接收并输出响应内容。

java怎么接收response返回内容

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942@qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: java怎么接收response返回内容
本文地址: https://solustack.com/53086.html

相关推荐:

网友留言:

我要评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。