import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.net.ssl.SSLContext;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;
public class AppTest {
@Test
public void test() throws Exception {
String url = "https://127.0.0.1:8888/cmcc";
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient httpClient = null;
if (url.startsWith("https")) {
File cert = new File("D:\\test\\logs\\cert.jks");
String keystore = "mocohttps";
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, NoopHostnameVerifier.INSTANCE);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
} else {
httpClient = HttpClients.createDefault();
}
try (CloseableHttpClient _httpClient = httpClient;
CloseableHttpResponse res = _httpClient.execute(httpGet);) {
if (res != null) {
StatusLine sl = res.getStatusLine();
if (sl != null) {
System.out.println(sl.getStatusCode());
StringBuilder builder = new StringBuilder();
try (InputStream is = res.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);) {
String line = br.readLine();
while(line != null) {
builder.append(line);
line = br.readLine();
}
System.out.println("响应结果:" + builder.toString());
}
}
}
}
}
}