java怎么接收response返回内容

35次阅读
没有评论

共计 1959 个字符,预计需要花费 5 分钟才能阅读完成。

在 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 请求,并接收并输出响应内容。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计1959字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)