java http Response对象常用方法的使用案例
时间: 2024-06-08 10:08:39 浏览: 8
下面是一个使用 Java 的 HTTP Response 对象的常用方法的示例:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpResponseExample {
public static void main(String[] args) throws IOException {
// 创建 URL 对象
URL url = new URL("http://www.example.com");
// 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方法
conn.setRequestMethod("GET");
// 获取响应代码
int responseCode = conn.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 获取响应内容
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 输出响应内容
System.out.println(response.toString());
// 获取响应头信息
String contentType = conn.getHeaderField("Content-Type");
System.out.println("Content-Type : " + contentType);
// 断开连接
conn.disconnect();
}
}
```
在这个例子中,我们首先创建一个 `URL` 对象,然后使用 `openConnection()` 方法打开连接。我们设置了请求方法为 `GET`,并使用 `getResponseCode()` 方法获取响应代码。我们然后从响应中读取内容,并输出到控制台。最后,我们使用 `getHeaderField()` 方法获取响应头信息,然后断开连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)