如何使用Java HttpURLConnection
The steps to send an HTTP request in Java using HttpURLConnection are as follows:
- Create a URL object and specify the URL address you want to request.
- establish a connection
- Convert the URLConnection object to an HttpURLConnection object because it is a subclass of URLConnection.
- use the setRequestMethod() method
- specify a property for the request
- enableInput()
- Enable output streaming.
- establish a connection
- 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.
- obtain the response code
- If the response status code is 200, it means the request was successful and you can access the response data.
- retrieve the input stream
- BufferedReader is a class used for reading text from a character-input stream in Java.
- 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.