1.需要引用以下依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
2.httpUtil帮助类
public class HttpUtil {
private static final Log logger = LogFactory.getLog(HttpUtil.class);
public static final int Format_KeyValue = 0;
public static final int Format_Json = 1;
private static RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
.setExpectContinueEnabled(Boolean.TRUE)
.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
/**
* 创建HttpClient客户端
* @param isHttps
* @return
*/
public static CloseableHttpClient createClient(boolean isHttps) {
if (isHttps) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream instream = new FileInputStream(new File("D:/ssl/test.keystore"));
trustStore.load(instream, "test".toCharArray());
// Trust own CA and all self-signed certs
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilde
. <ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTA.
register("https", socketFactory).build();
// 创建ConnectionManager,添加Connection配置信息
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig).build();
return closeableHttpClient;
} catch (KeyManagementException e) {
e.printStackTrace();
logger.error("创建HTTPS客户端异常");
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (CertificateException e) {
logger.error("创建HTTPS客户端异常");
e.printStackTrace();
throw new RuntimeException(e);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (KeyStoreException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
} else {
return HttpClientBuilder.create().build();
}
}
/**
* 调用Get接口
* @param url 接口地址
* @return
*/
public static String sendGet(String url) {
return sendGet(url, createClient(true));
}
/**
* 调用Get接口
* @param url 接口地址
* @param httpClient
* @return
*/
public static String sendGet(String url, CloseableHttpClient httpClient) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpGet request = null;
try {
request = new HttpGet(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
} finally {
if (request != null)
request.releaseConnection();
}
return null;
}
/**
* 调用Post接口
* @param httpClient
* @param url 接口地址
* @param entity
* @return
*/
public static String sendPost(CloseableHttpClient httpClient, String url, StringEntity entity) {
if (url == null || "".equals(url)) {
logger.error("接口地址为空");
return null;
}
HttpPost request = null;
try {
request = new HttpPost(url);
if (httpClient == null) {
logger.error("HttpClient实例为空");
return null;
}
request.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("访问接口失败,接口地址为:" + url);
} finally {
if (request != null)
request.releaseConnection();
}
return null;
}
/**
* 调用Post接口
* @param httpClient
* @param url 接口地址
* @param user
* @return
*/
public static String sendPost(CloseableHttpClient httpClient, String url, User user) {
StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
return sendPost(httpClient,url,entity);
}
public static InputStream downloadRemoteFile(CloseableHttpClient httpClient,String apiUrl,User user) {
InputStream is = null;
HttpPost request = new HttpPost(apiUrl);
try {
if (httpClient == null) {
return null;
}
StringEntity entity = new StringEntity(JSON.toJSONString(user), "UTF-8");
request.setEntity(entity);
CloseableHttpResponse httpResponse = httpClient.execute(request);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity result = httpResponse.getEntity();
if (null != result) {
// 获取返回内容
is = result.getContent();
}
} else if(statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED){
request.abort();
}
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
}
3.service业务层调用
public class testService(){
//调用sendGet
public Test testSendGet(long id){
Test test= new Test();
String url ="https://TestProject/restful/queryById?Id=" + Id;
String rString = HttpUtil.sendGet(url);
if(null != rString && !rString.isEmpty() && !rString.equals("[]")) {
test = JSONObject.parseObject(rString,Test.class);
}
}
//调用sendPost
public Test testSendPost(PageInfo<Test> page,long id){
List<Test> list= new ArrayList<Test>);
CloseableHttpClient client = HttpUtil.createClient(true);
String url ="https://TestProject/restful/all?Id=" + Id;
String rString = HttpUtil.sendPost(client,url,page);;
if(null != rString && !rString.isEmpty() && !rString.equals("[]")) {
list = JSONObject.parseArray(rString,Test.class);
}
}
//调用downloadRemoteFile下载文件
public void testDownloadRemoteFile(User user,long id){
List<Test> list= new ArrayList<Test>);
CloseableHttpClient client = HttpUtil.createClient(true);
String url ="https://TestProject/restful/downloads?Id=" + Id;
InputStream inputStream = HttpUtil.downloadRemoteFile(client,url,user);
OutputStream outputStream = null;
// 打开目的输入流,不存在则会创建
File file = new File(SbConstants.BASELINE_DOWNLOAD_DIR + relativePath);
// 判断文件夹是否存在
if (!file.exists()) {
// 如果文件夹不存在,则创建新的的文件夹
file.mkdirs();
}
long beginTime = System.currentTimeMillis();
try {
outputStream = new FileOutputStream(SbConstants.BASELINE_DOWNLOAD_DIR + baseline.getFilePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 将输入流is写入文件输出流fos中
byte[] bytes = new byte[1024];
try {
int ch = inputStream.read(bytes, 0, 1024);
while (ch != -1) {
outputStream.write(bytes);
ch = inputStream.read(bytes, 0, 1024);
}
} catch (IOException e1) {
e1.printStackTrace();
} finally {
// 关闭输入流等(略)
try {
outputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
原文:https://www.cnblogs.com/Bud-blog/p/12146282.html