import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpsExample {
public static void main(String[] args) {
try {
// 定义要调用的HTTPS接口URL
String url = "https://api.example.com/data";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// 设置请求方法为GET
con.setRequestMethod("GET");
// 设置请求头(可选)
con.setRequestProperty("User-Agent", "JavaHttpExample/1.0");
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
// 读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应内容
System.out.println("Response: " + response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
java.io, java.net 和 javax.net.ssl 包来处理 HTTPS 请求。HttpsURLConnection 来打开与指定 URL 的连接。setRequestMethod("GET") 设置请求方法为 GET。User-Agent。getResponseCode() 获取服务器的响应码。BufferedReader 读取服务器返回的内容。如果你需要 POST 请求或其他更复杂的操作,可以根据需求调整代码。
上一篇:java threadpoolexecutor创建线程池
下一篇:java urldecoder
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站