java requset 获取http和https
时间: 2024-06-08 14:05:59 浏览: 72
Java中可以使用HttpURLConnection类来获取HTTP和HTTPS请求。以下是一个简单的示例:
```
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpTest {
public static void main(String[] args) {
try {
// HTTP请求
URL url = new URL("http://www.example.com");
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
int responseCode = httpConnection.getResponseCode();
System.out.println("HTTP Response Code: " + responseCode);
// HTTPS请求
url = new URL("https://www.example.com");
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setRequestMethod("GET");
responseCode = httpConnection.getResponseCode();
System.out.println("HTTPS Response Code: " + responseCode);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的示例中,我们使用`HttpURLConnection`类来打开一个URL连接,并向服务器发送HTTP和HTTPS请求。在每个请求中,我们设置请求方法为“GET”,并获取服务器的响应代码。请注意,HTTPS请求需要使用受信任的证书进行身份验证。如果证书无效或过期,将会抛出异常。
阅读全文