废话少说,直接上代码。
httpclient get请求,post请求类似
public static String getRequest(String url,String params, String contentType){
StringBuilder response = new StringBuilder();
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (x509CertChain, authType) -> true).build();
CloseableHttpClient httpClient = HttpClientBuilder.create()
.setSSLContext(sslContext)
.setConnectionManager(new PoolingHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext,
NoopHostnameVerifier.INSTANCE))
.build()
)).build();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization",params);
httpGet.setHeader("Content-Type", contentType);
//执行请求
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)){
org.apache.http.HttpEntity entity = httpResponse.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
} catch( Exception e){
e.printStackTrace();
}
return response.toString();
}