调用微信公众平台新增永久图文素材接口时,由于微信会过滤外部的图片链接,所以开发者需要提前将图片上传获得URL,放在图文内容中使用。本文提供了使用java代码,逐个获取图文内容中的图片,并上传图片和替换图文内容中的url(另附java模拟使用curl命令,用FORM表单方式上传一个图片方法)。
//替换字符串中的src
//ynr 图文内容
//index 从第几个字符开始替换
private String thsrc(String ynr,int index){
int srcStart = ynr.indexOf("src=\"",index); //获取src出现的位置
int srcEnd = ynr.indexOf("\"",srcStart+7);
srcStart = srcStart + 5;
String src = ynr.substring(srcStart,srcEnd); //获取图片路径
//执行上传图片方法
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+ AccessToken.getAccess_token();
String scptjg = postFile(url,src);
JSONObject scptjgJson = JSONObject.fromObject(scptjg);
String newPath = scptjgJson.getString("url");
//替换字符串中该图片路径
ynr = ynr.replace(src, newPath);
//查看字符串下方是否还有img标签
int sfhyImg = ynr.indexOf("<img",srcEnd);
if(sfhyImg==-1){
return ynr;
}else{
return thsrc(ynr, srcEnd);
}
}
//上传图片素材/上传图文消息内的图片获取URL
// url - 路径
//filePath 图片绝对路径
private String postFile(String url, String filePath) {
File file = new File(filePath);
if (!file.exists())
return null;
String result = "";
try {
URL url1 = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Cache-Control", "no-cache");
String boundary = "-----------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream output = conn.getOutputStream();
output.write(("--" + boundary + "\r\n").getBytes());
output.write(
String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName())
.getBytes());
output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
byte[] data = new byte[1024];
int len = 0;
FileInputStream input = new FileInputStream(file);
while ((len = input.read(data)) > -1) {
output.write(data, 0, len);
}
output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
output.flush();
output.close();
input.close();
InputStream resp = conn.getInputStream();
StringBuffer sb = new StringBuffer();
while ((len = resp.read(data)) > -1)
sb.append(new String(data, 0, len, "utf-8"));
resp.close();
result = sb.toString();
} catch (ClientProtocolException e) {
logger.error("postFile,不支持http协议", e);
} catch (IOException e) {
logger.error("postFile数据传输失败", e);
}
return result;
}