package com.weshare.argus.service.impl;
import com.alibaba.dubbo.common.utils.IOUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.weshare.argus.common.adapter.RestTemplateUtil; import com.weshare.argus.common.config.SystemConfig; import com.weshare.argus.common.contants.Constant; import com.weshare.argus.service.UploadService; import com.weshare.argus.utils.Result; import com.weshare.argus.utils.WeshareTokenHelper; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import javax.net.ssl.SSLContext; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.charset.Charset; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
_/** _ * Created by 陈稳 on 2018/6/15. */ @Service public class UploadServiceImpl implements UploadService { private static final Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);
@Autowired
private RestTemplateUtil restTemplateUtil;
@Override
public void uploadFile(MultipartFile file, String paramJson, String originalUrl) throws Exception { try { _// 1-1, 根据originalUrl解析服务器名,urlSuffix _ if (originalUrl.startsWith("/") && originalUrl.length() > 1) { originalUrl = originalUrl.substring(1); } _// 获取服务项目名 _ String projectName = originalUrl.substring(0, originalUrl.indexOf("/")); String urlSuffix = originalUrl.substring(originalUrl.indexOf("/"));
_// 1-2,根据服务项目名获取对应的ak,sk
_ // 根据服务器项目名获取想对应的url,ak,sk等信息 String urlPrefix = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_URL_COMMON); String requestUrl = urlPrefix + originalUrl; String ak = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_AK_COMMON); String sk = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_SK_COMMON);
TrustStrategy acceptingTrustStrategy = (X509Certificate\[\] chain, String authType) -> **true**;
SSLContext sslContext = org.apache.http.ssl.SSLContexts._custom_()
.loadTrustMaterial(**null**, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = **new** SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients._custom_()
.setSSLSocketFactory(csf)
.build();
**if** (StringUtils._isEmpty_(paramJson)) {
paramJson = sk;
}
**int** expireTime = (**int**) (System._currentTimeMillis_() / 1000 \+ 30 \* 60);
WeshareTokenHelper tokenHelper = **new** WeshareTokenHelper(ak, sk);
_// 设置消息头
_ String generateToken = tokenHelper.generateToken(urlSuffix, "POST", "", paramJson, expireTime);
String fileName = file.getOriginalFilename();
HttpPost httpPost = **new** HttpPost(requestUrl);
MultipartEntityBuilder builder = MultipartEntityBuilder._create_();
builder.addBinaryBody(**"file"**, file.getInputStream(), ContentType._MULTIPART\_FORM\_DATA_, fileName);_// 文件流
_ builder.addTextBody("paramJson", paramJson, ContentType.APPLICATION_JSON); builder.addTextBody("token", generateToken, ContentType.APPLICATION_JSON); HttpEntity entity = builder.build(); httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);_// 执行提交
_ HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { _// 将响应内容转换为字符串 _ String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8")); logger.info("uploadFile | Result is : {}" + result); } } catch (Exception e) { e.printStackTrace(); throw e; } }
@Override
public void downloadFile(HttpServletResponse response, String paramJson, String originalUrl) throws Exception { try { _// 1-1, 根据originalUrl解析服务器名,urlSuffix _ if (originalUrl.startsWith("/") && originalUrl.length() > 1) { originalUrl = originalUrl.substring(1); } _// 获取服务项目名 _ String projectName = originalUrl.substring(0, originalUrl.indexOf("/")); String urlSuffix = originalUrl.substring(originalUrl.indexOf("/"));
_// 1-2,根据服务项目名获取对应的ak,sk
_ // 根据服务器项目名获取想对应的url,ak,sk等信息 String urlPrefix = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_URL_COMMON); String requestUrl = urlPrefix + originalUrl; String ak = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_AK_COMMON); String sk = SystemConfig.getSystemConfigValue(projectName + Constant.SERVER_SK_COMMON);
**if** (StringUtils._isEmpty_(paramJson)) {
paramJson = sk;
}
**int** expireTime = (**int**) (System._currentTimeMillis_() / 1000 \+ 30 \* 60);
WeshareTokenHelper tokenHelper = **new** WeshareTokenHelper(ak, sk);
_// 设置消息头
_ String generateToken = tokenHelper.generateToken(urlSuffix, "POST", "", paramJson, expireTime);
_// 设置消息头
_ Map<String, String> headers = new HashMap<>(10);
_// 设置请求体
_ JSONObject bodyObj = new JSONObject();
bodyObj.put("token", generateToken);
if (!StringUtils.isEmpty(paramJson)) {
bodyObj.put("paramJson", paramJson);
} else {
bodyObj.put("paramJson", sk);
}
ResponseEntity<byte**[]> responseEntity = restTemplateUtil.postForEntity2(requestUrl, headers, bodyObj);
_// 如果结果返回正常的情况下下载文件
_ if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
byte[] result = responseEntity.getBody();
HttpHeaders httpHeaders = responseEntity.getHeaders();
String contentType = String.valueOf(responseEntity.getHeaders().getContentType());
List
package com.weshare.argus.common.adapter;
import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate;
import java.util.Map;
_/** _ * <类功能简述> * * @author _chenwen _ */ @Component public class RestTemplateUtil {
@Autowired
private RestTemplate restTemplate;
**public**<I\> ResponseEntity<JSONObject> postForEntity(String url, Map<String, String> headerMap, I input) {
_// 设置消息头
_ HttpHeaders headers = new HttpHeaders();
**for** (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
_// 设置请求参数
_ HttpEntity httpEntity = new HttpEntity<>(input, headers);
**return** **restTemplate**.postForEntity(url, httpEntity, JSONObject.**class**);
}
**public**<T\> ResponseEntity<**byte**\[\]> postForEntity2(String url, Map<String, String> headerMap, T input) {
_// 设置消息头
_ HttpHeaders headers = new HttpHeaders();
**for** (Map.Entry<String, String> entry : headerMap.entrySet()) {
headers.add(entry.getKey(), entry.getValue());
}
_// 设置请求参数
_ HttpEntity httpEntity = new HttpEntity<>(input, headers);
**return** **restTemplate**.postForEntity(url, httpEntity, **byte**\[\].**class**);
}
}
<**beans** **xmlns****="http://www.springframework.org/schema/beans" ** **xmlns:****xsi****="http://www.w3.org/2001/XMLSchema-instance" ** **xsi****:schemaLocation****="http://www.springframework.org/schema/beans ** **http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"**\>
_<!--rest template config-->
_ <**bean** **id****="simpleClientHttpRequestFactory"** **class****="org.springframework.http.client.SimpleClientHttpRequestFactory"**> <**property** **name****="readTimeout"** **value****="60000"**/> <**property** **name****="connectTimeout"** **value****="5000"**/> </**bean**> <**bean** **id****="restTemplate"** **class****="org.springframework.web.client.RestTemplate"**> <**constructor-arg** **ref****="simpleClientHttpRequestFactory"**/> <**property** **name****="messageConverters"**> <**list**> <**bean** **class****=" com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"**> <**property** **name****="supportedMediaTypes"**> <**list**> <**value**>application/json;charset=UTF-8</**value**> <**value**>text/plain;charset=UTF-8</**value**> </**list**> </**property**> </**bean**> <**bean** **class****="org.springframework.http.converter.FormHttpMessageConverter"**/> <**bean** **class****="org.springframework.http.converter.ByteArrayHttpMessageConverter"**/> <**bean** **class****="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"**> <**property** **name****="supportedMediaTypes"**> <**list**> <**value**>application/json;charset=UTF-8</**value**> </**list**> </**property**> </**bean**> <**bean** **class****="org.springframework.http.converter.StringHttpMessageConverter"**> <**property** **name****="supportedMediaTypes"**> <**list**> <**value**>text/plain;charset=UTF-8</**value**> <**value**>application/json;charset=UTF-8</**value**> </**list**> </**property**> </**bean**> </**list**> </**property**> </**bean**>
</**beans**>