java怎么接收response返回内容

   2025-02-22 5230
核心提示:在Java中可以使用HttpURLConnection或者HttpClient来接收response返回内容。使用HttpURLConnection的示例代码如下:import java.

在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 {// 关闭HttpClienthttpClient.close();} catch (IOException e) {e.printStackTrace();}}}}

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言