import ohos.net.httpurlconnection.HttpURLConnection;
import ohos.net.httpurlconnection.HttpURLConnectionUtils;
import ohos.net.httpurlconnection.HttpHeader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("https://www.example.com");
// 打开HttpURLConnection连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法(GET、POST等)
connection.setRequestMethod("GET");
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 获取响应头信息
HttpHeader header = connection.getHeaderFields();
System.out.println("Response Headers: " + header);
// 读取响应数据
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印响应数据
System.out.println("Response Data: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个例子中,首先创建了一个 URL 对象,表示要访问的资源。然后,通过 openConnection 方法获取 HttpURLConnection 对象,设置请求方法为 "GET",获取响应码、响应头和响应数据,最后关闭连接。
请注意,以上示例代码仅供演示目的,实际使用时可能需要根据具体需求进行适当的修改和扩展。鸿蒙OS的网络编程可能会有一些特定的限制和规定,具体可以参考官方文档或开发者手册。
转载请注明出处:http://www.zyzy.cn/article/detail/2819/鸿蒙OS