📜  HttpURLConnection 示例 (1)

📅  最后修改于: 2023-12-03 14:42:01.294000             🧑  作者: Mango

HttpURLConnection 示例

HttpURLConnection 是 Java 中用来进行 HTTP 基础网络操作的类,使用方式类似于浏览器,可以发送 HTTP 请求和接收响应。本文将介绍 HttpURLConnection 的使用方法,并给出示例代码。

创建 HttpURLConnection

创建 HttpURLConnection 对象使用 URL.openConnection() 方法,如下所示:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
设置请求方法和属性

HttpURLConnection 默认使用 GET 方法发送请求,可以通过 setRequestMethod() 方法设置为 POST 或其他方法。

connection.setRequestMethod("POST");

可以通过 setRequestProperty() 方法设置请求头属性,如设置 Content-Type。

connection.setRequestProperty("Content-Type", "application/json");
发送请求数据

如果请求绑定了数据,可以使用 setDoOutput() 方法开启发送数据模式。多数情况下需要发送字节流或字符流,可以使用 OutputStream 或 Writer 输出流进行发送。

connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestData.getBytes());
接收响应数据

HttpURLConnection 可以通过 getResponseCode() 方法获取响应码,通过 getInputStream() 或 getErrorStream() 方法获取响应流。如果响应码是 200(OK),可以通过读取响应流获取响应字符串。

int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
    InputStream inputStream = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
}
完整示例代码
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpExample {
    public static void main(String[] args) throws IOException {
        String requestData = "{\"key\": \"value\"}";
        StringBuilder response = new StringBuilder();
        URL url = new URL("http://example.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(requestData.getBytes());
        int statusCode = connection.getResponseCode();
        if (statusCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            System.out.println(response);
        } else {
            InputStream errorStream = connection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            System.err.println(response);
        }
    }
}

以上就是 HttpURLConnection 的基本使用方法和示例代码。