如何使用Java HttpURLConnection

The steps to send an HTTP request in Java using HttpURLConnection are as follows:

  1. Create a URL object and specify the URL address you want to request.
  2. establish a connection
  3. Convert the URLConnection object to an HttpURLConnection object because it is a subclass of URLConnection.
  4. use the setRequestMethod() method
  5. specify a property for the request
  6. enableInput()
  7. Enable output streaming.
  8. establish a connection
  9. If there is a need to send a request body, you can achieve this by obtaining the output stream and writing the request body data.
  10. obtain the response code
  11. If the response status code is 200, it means the request was successful and you can access the response data.
  12. retrieve the input stream
  13. BufferedReader is a class used for reading text from a character-input stream in Java.
  14. unplug()

Here is a simple example code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionExample {
    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://example.com");
            
            // 打开URL连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法
            connection.setRequestMethod("GET");
            
            // 设置请求头信息
            connection.setRequestProperty("User-Agent", "Mozilla/5.0");
            
            // 发送请求
            connection.connect();
            
            // 获取响应状态码
            int statusCode = connection.getResponseCode();
            
            // 判断是否请求成功
            if (statusCode == HttpURLConnection.HTTP_OK) {
                // 获取响应输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                
                // 读取响应数据
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                
                // 输出响应数据
                System.out.println(response.toString());
            } else {
                System.out.println("请求失败,状态码:" + statusCode);
            }
            
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Please note that the URL address in the example above is for demonstration purposes only, and needs to be replaced with the actual URL address when used.

bannerAds