/**
* 公共method 替换 内容图片地址
* json化上传内容 (遗留问题-特殊符合被转译)
* @param groupWxMessage
* @param access_token
* @return
* @throws IOException
*/
net.sf.json.JSONObject getJsonObject(GroupWxMessage groupWxMessage, String access_token) throws IOException {
String content = groupWxMessage.getContent();
String key ="src=\"";
int a = content.indexOf(key);
if(a != -1){
String thsrcContent = thsrc(content, a, access_token);
groupWxMessage.setContent(thsrcContent);
}
List<TuWenOutDTO> articles = new ArrayList<TuWenOutDTO>();
TuWenOutDTO article = new TuWenOutDTO();
article.setTitle(groupWxMessage.getTitle());
article.setThumb_media_id(groupWxMessage.getThumbMediaId());
article.setShow_cover_pic(groupWxMessage.getShowCoverPic());
article.setDigest(groupWxMessage.getDigest());
article.setContent_source_url(groupWxMessage.getContentSourceUrl());
article.setContent(groupWxMessage.getContent());
article.setAuthor(groupWxMessage.getAuthor());
articles.add(article);
List<TuWenOutDTO> list = new ArrayList<>();
list.add(article);
Map<String, Object> params = new HashMap<>();
params.put("articles", list);
net.sf.json.JSONObject json1 = net.sf.json.JSONObject.fromObject(params);
return json1;
}
/**
* 内容Content中图片地址替换
* @param content
* @param index
* @param access_token
* @return
* @throws IOException
*/
private String thsrc(String content,int index,String access_token) throws IOException {
int srcStart = content.indexOf("src=\"",index); //获取src出现的位置
int srcEnd = content.indexOf("\"",srcStart+62);
srcStart = srcStart + 5;
String src = content.substring(srcStart,srcEnd); //获取图片路径
//执行上传图片方法
String img = saveUrlAs(src);
net.sf.json.JSONObject scptjgJson = wxPhotoUpload.addContentPicture(img, "image", access_token);
String newPath = scptjgJson.getString("url");
//替换字符串中该图片路径
content = content.replace(src, newPath);
//查看字符串下方是否还有img标签
int sfhyImg = content.indexOf("<img",srcEnd);
if(sfhyImg==-1){
return content;
}else{
return thsrc(content, srcEnd,access_token);
}
}
/**
* 通过url生成本地临时文件
* @param photoUrl
* @return
*/
public static String saveUrlAs(String photoUrl) throws IOException {
//此方法只能用户HTTP协议
String fileName = dateToTimestamp(DateUtil.getTime()) + MadeKey.getKey() + ".jpg";
System.out.println(fileName);
URL url = new URL(photoUrl);
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
DataInputStream in = new DataInputStream(connection.getInputStream());
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
out.close();
in.close();
return fileName;
}