HttpURLConnection网络访问学习收获
时间: 2024-02-21 21:54:55 浏览: 60
HttpURLconnection
HttpURLConnection是Java中用于进行HTTP网络访问的类。它提供了一种简单而灵活的方式来与服务器进行通信,并获取服务器返回的数据。使用HttpURLConnection可以发送GET和POST请求,以及设置请求头和请求参数等。
通过使用HttpURLConnection,我们可以实现以下功能:
1. 建立连接并发送GET请求:
```java
URL url = new URL("http://ip地址:端口/资源地址");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
```
2. 获取服务器返回的结果:
```java
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();
connection.disconnect();
String result = response.toString();
```
3. 发送POST请求:
```java
URL url = new URL("http://ip地址:端口/资源地址");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write("参数".getBytes());
outputStream.flush();
outputStream.close();
```
4. 设置请求头:
```java
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer token");
```
5. 设置请求参数:
```java
String params = "key1=value1&key2=value2";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
```
通过学习和使用HttpURLConnection,我们可以轻松地进行网络访问,并获取服务器返回的数据,从而实现与服务器的交互和数据传输。
阅读全文