Commit 4fe8716d authored by kongfm's avatar kongfm

修复BUG 更新从微信服务器下载资源接口

parent 95a5ec19
......@@ -35,4 +35,11 @@ public interface IWechatService {
*/
JSONObject sendWechatModelMessage(String openId, WechatMessageDto wechatMessageDto);
/**
* 根据多媒体id 获取微信图片
* @param mediaId
* @return
*/
String getWechatPicByMediaId(String mediaId);
}
......@@ -20,6 +20,10 @@
<artifactId>amos-boot-module-common-biz</artifactId>
<version>${amos-biz-boot.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
</dependencies>
</project>
......@@ -45,6 +45,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
......@@ -509,13 +510,24 @@ public class WechatController extends BaseController {
return ResponseHelper.buildResponse(urlString);
}
/**
* 微信端图片上传
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@GetMapping(value = "/downloadWechatPic/{mediaId}")
@ApiOperation(httpMethod = "GET", value = "微信公众号从微信服务器下载图片到自己服务器", notes = "微信公众号从微信服务器下载图片到自己服务器")
public ResponseModel<String> uploadImage(@PathVariable String mediaId) {
if (ValidationUtil.isEmpty(mediaId)){
throw new BadRequest("参数校验失败.");
}
String urlString = wechatService.getWechatPicByMediaId(mediaId);
return ResponseHelper.buildResponse(urlString);
}
private WechatMyBussinessDto getBussinessDtoById(Long alertId) {
WechatMyBussinessDto temp = iAlertCalledService.getBussinessInfoById(alertId);
List<AlertFormValue> paperList = null;
Map<String, List<AttachmentDto>> imgMap = null;
List<AttachmentDto> imgDtos = null;
......@@ -635,4 +647,22 @@ public class WechatController extends BaseController {
}
return temp;
}
/**
* 微信端图片上传
*
* @return
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@PostMapping(value = "/testWechatFile")
@ApiOperation(httpMethod = "POST", value = "微信公众号上传图片", notes = "微信公众号上传图片")
public ResponseModel<String> testWechatFile(@ApiParam(value = "图片", required = true)@RequestParam MultipartFile file) {
if (ValidationUtil.isEmpty(file)){
throw new BadRequest("参数校验失败.");
}
String accessToken = wechatService.getAccessToken();
String getPicUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=image";
String url = HttpUtils.doPostWithFile(getPicUrl,file,"media",accessToken,"image");
return ResponseHelper.buildResponse(url);
}
}
......@@ -7,12 +7,19 @@ import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMessageDto;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatService;
import com.yeejoin.amos.boot.module.tzs.biz.utils.HttpUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
......@@ -146,5 +153,28 @@ public class WechatServiceImpl implements IWechatService {
return response;
}
@Override
public String getWechatPicByMediaId(String mediaId) {
String accessToken = this.getAccessToken();
String getPicUrl = wechatUrl + "/cgi-bin/media/get?access_token=" + accessToken + "&media_id=" + mediaId;
Map<String, Object> result = HttpUtils.doGetDownload(getPicUrl);
if(result.get("bytes") == null) {
throw new BadRequest("获取附件失败");
}
byte[] bytes = (byte[]) result.get("bytes");
String fileName = (String) result.get("filename");
String urlString="";
MultipartFile file = new MockMultipartFile(fileName,fileName,"application/octet-stream" ,bytes);
FeignClientResult<Map<String, String>> date = Systemctl.fileStorageClient.updateCommonFile(file);
if (date != null) {
Map<String, String> map = date.getResult();
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
urlString=it.next();
}
}
return urlString;
}
}
\ No newline at end of file
package com.yeejoin.amos.boot.module.tzs.biz.utils;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
......@@ -12,7 +14,11 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
......@@ -21,11 +27,15 @@ import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
......@@ -358,6 +368,114 @@ public class HttpUtils {
}
/**
* 发送get请求并且获取下载字节流
* @param apiUrl
* @return
*/
public static Map<String, Object> doGetDownload(String apiUrl) {
Map<String, Object> result = new HashMap<>();
InputStream inputStream = null;
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
HttpGet httpGet = new HttpGet(apiUrl);
CloseableHttpResponse response = null;
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
try {
response = httpClient.execute(httpGet);
Header[] heads = response.getHeaders("Content-disposition");
HeaderElement[] elements = heads[0].getElements();
for (HeaderElement el : elements) {
NameValuePair pair = el.getParameterByName("filename");
result.put("filename",pair.getValue());
}
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = inputStream.read(buff, 0, buff.length)) > 0) {
swapStream.write(buff, 0, rc);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
result.put("bytes",swapStream.toByteArray());
return result;
}
/**
* 发送上传post 文件
* @param apiUrl
* @param file
* @return
*/
public static String doPostWithFile(String apiUrl, MultipartFile file, String fileParam, String token , String type) {
CloseableHttpClient httpClient = null;
if (apiUrl.startsWith("https")) {
httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createDefault();
}
String httpStr = null;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
try {
httpPost.addHeader("Connection", "keep-alive");
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Content-Type", "multipart/form-data;boundary=------------7da2e536604c8");
httpPost.addHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setBoundary("------------7da2e536604c8")
.setCharset(Charset.forName("UTF-8"))
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("type", type);
// 设置access_token,
builder.addTextBody("access_token", token);
String fileName = null;
fileName = file.getOriginalFilename();
builder.addBinaryBody(fileParam, file.getBytes(), ContentType.APPLICATION_OCTET_STREAM, fileName);// 文件流
//解决中文乱码
// for (Map.Entry<String, Object> entry : params.entrySet()) {
// if(entry.getValue() == null) {
// continue;
// }
// // 类似浏览器表单提交,对应input的name和value
// builder.addTextBody(entry.getKey(), entry.getValue().toString());
// }
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);// 执行提交
HttpEntity result = response.getEntity();
httpStr = EntityUtils.toString(result, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (response != null) {
try {
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return httpStr;
}
/**
* 创建SSL安全连接
*
* @return
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment