请帮我写一个java工具类,内容是支持HTTP以及HTTPS调用的工具类
时间: 2024-04-04 11:30:40 浏览: 79
好的,以下是一个简单的 Java 工具类,支持 HTTP 和 HTTPS 调用:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HttpUtils {
// HTTP GET 请求
public static String sendGet(String urlString) {
String result = "";
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
reader.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
// HTTPS GET 请求
public static String sendHttpsGet(String urlString) {
String result = "";
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} }, new java.security.SecureRandom());
URL url = new URL(urlString);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
reader.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
```
使用时,可以通过以下方式调用:
```java
String httpResult = HttpUtils.sendGet("http://www.example.com");
String httpsResult = HttpUtils.sendHttpsGet("https://www.example.com");
```
需要注意的是,HTTPS 请求需要进行 SSL 验证,上述代码中省略了证书验证,不建议在生产环境中使用。如果需要进行证书验证,请参考 Java 官方文档中的示例代码:[Java HTTPS Client Example](https://docs.oracle.com/javase/tutorial/security/apisign/step3.html)。
阅读全文