1.MethodEnum枚举
public enum MethodEnum {
GET("GET"),
POST("POST"),
PUT("PUT"),
DELETE("DELETE");
private String methodName;
MethodEnum(String methodName) {
this.methodName = methodName;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
}
2.MyX509TrustManager用于https请求
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
3.HttpsUtil工具类
public final class HttpsUtil {
private HttpsUtil() {}
public static String request(String address, MethodEnum methodEnum, Map<String, String> headers, String body) {
StringBuilder sb = new StringBuilder();
HttpsURLConnection httpUrlConn = null;
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(address);
httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setRequestProperty("Charset", "UTF-8");
if (Objects.nonNull(headers) && headers.size() > 0) {
Set<Entry<String, String>> entries = headers.entrySet();
for (Entry<String, String> entry : entries) {
httpUrlConn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(methodEnum.getMethodName());
if (MethodEnum.GET == methodEnum) {
httpUrlConn.connect();
}
if (StringUtils.isNotBlank(body)) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(body.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String partResult;
while ((partResult = bufferedReader.readLine()) != null) {
sb.append(partResult);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
return sb.toString();
} catch (Exception e) {
throw new RuntimeException("网络请求出错");
} finally {
if (httpUrlConn != null) {
httpUrlConn.disconnect();
}
}
}
}
4.测试
public static void main(String[] args) throws Exception {
Map<String, String> headers = new HashMap<>(1);
// headers.put("Content-Type", "application/json");
// headers.put("Accept", "application/json");
headers.put("Accept", "text/html");
String request = request("https://www.baidu.com", MethodEnum.GET, headers, null);
System.out.println(request);
}