分为Http和Https两种。
public class SSLUtils {
public static String getHttp(String url) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
} catch (IOException e) {
throw e;
}
HttpEntity entity = response.getEntity();
String result = null;
try {
result = EntityUtils.toString(entity);
} catch (ParseException | IOException e) {
throw e;
}
return result;
}
public static String getHttps(String url) throws IOException {
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = createSSLInsecureClient().execute(post);
return stream2Str(response.getEntity().getContent());
}
private static String stream2Str(InputStream inputStream) throws IOException {
StringBuilder sbu = new StringBuilder();
InputStreamReader inputStreamReader;
try {
inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader reader = new BufferedReader(inputStreamReader);
String line;
while ((line = reader.readLine()) != null) {
sbu.append(line);
}
return sbu.toString();
} catch (IOException e) {
throw e;
}
}
private static CloseableHttpClient createSSLInsecureClient() {
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509Certificates, s) -> true).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (Exception e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
}