前面拿到了token令牌,那么后面的第二部就是讲我要群发的内容中的所有图片的链接上传到微信服务器上。这里所有的图片是服务器上的图片,或者是我们自带的项目中编辑器自带的样式。要注意上传的格式。这里上传的URL是https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=WeiXinAccess。这里上传的是永久素材。下面是上传代码:
/**
* 微信上传图片
urlStr:微信上传的URL
imgURLStr:文章图片的URL
*
*/
private static String formUpload1(String urlStr, String imgURLStr) {
//定义个变量,用于返回结果
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------"; // boundary就是request头和上传文件内容的分隔符
try {
URL url1 = new URL(urlStr);
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("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// file
URL urlFile = new URL(imgURLStr);
String fileName = urlFile.getPath();
String host = urlFile.getHost();
int i = imgURLStr.indexOf(host);
String httpStr = imgURLStr.substring(0,i);
String[] strs = fileName.split("/");
String filePath2 =httpStr+ urlFile.getHost();
//重构URL,将URL中的中文转成UTF-8的格式
for(String str:strs){
if(!("".equals(str))){
filePath2 = filePath2+"/"+URLEncoder.encode(str,"UTF-8");
}
}
URL url2 = null;
boolean bo = imgURLStr.contains("wx_fmt=");
url2 = new URL(filePath2);
String inputName = "";
String filename = url2.getFile();
host = url2.getHost();
String contentType = null;
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//下面是判断文件的格式,是jpg.gif还是png,这个因人而异,我判断做的有点繁琐,好多都绕了弯路,
if(bo){
String type = imgURLStr.split("wx_fmt=")[1];
//是135的编辑器
if("jpeg".equals(type)){
contentType = "image/jpg";
filename = uuid+".jpg";
}else if("png".equals(type)){
contentType = "image/png";
filename = uuid+".png";
}else if("gif".equals(type)){
contentType = "image/gif";
filename = uuid+".gif";
}else {
boolean bo2 = type.contains("&");
if(bo2){
String type1 = type.split("&")[0];
if("jpeg".equals(type1)){
contentType = "image/jpg";
filename = uuid+".jpg";
}else if("png".equals(type1)){
contentType = "image/png";
filename = uuid+".png";
}else if("gif".equals(type1)){
contentType = "image/gif";
filename = uuid+".gif";
}
}
}
}else {
if(host.contains("135editor")){
if(bo){
String type = imgURLStr.split("wx_fmt=")[1];
//是135的编辑器
if("jpeg".equals(type)){
contentType = "image/jpg";
filename = uuid+".jpg";
}else if("png".equals(type)){
contentType = "image/png";
filename = uuid+".png";
}else if("gif".equals(type)){
contentType = "image/gif";
filename = uuid+".gif";
}
}else{
int index = imgURLStr.lastIndexOf(".");
String imageType = imgURLStr.substring(index+1,imgURLStr.length());
if("jpeg".equals(imageType)){
contentType = "image/jpg";
filename = uuid+".jpg";
}else if("png".equals(imageType)){
contentType = "image/png";
filename = uuid+".png";
}else if("gif".equals(imageType)){
contentType = "image/gif";
filename = uuid+".gif";
}else if("jpg".equals(imageType)){
contentType = "image/jpg";
filename = uuid+".jpg";
}else {
contentType = "image/jpg";
filename = uuid+".jpg";
}
}
}else {
if (filename.endsWith(".png")) {
contentType = "image/png";
filename = uuid+".png";
}
if (filename.endsWith(".jpg")) {
contentType = "image/jpg";
filename = uuid+".jpg";
}
if (filename.endsWith(".gif")) {
contentType = "image/gif";
filename = uuid+".gif";
}
}
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
//构建要发送的头信息
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append(
"Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
//将服务器上的图片变成流输出到请求里
DataInputStream in = new DataInputStream(url2.openStream());
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
StringBuffer strBuf2 = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf2.append(line).append("\n");
}
res = strBuf2.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
上面方法的调用
/*
* 上传图文消息内的图片获取URL,
* @param file
* @param access
* @return
*/
public static String getUpWxImgUrl(String imgURL,String access) {
String url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=WeiXinAccess".replace("WeiXinAccess",access);
String jsonStr = formUpload1(url, imgURL);
String returnUrl = "";
if(jsonStr.indexOf("errcode") == -1) {
JSONObject jsonObject = new JSONObject(jsonStr);
returnUrl = jsonObject.get("url").toString();
}
return returnUrl;
}
这样就讲一个图片转换成了微信服务器上的图片,拿到URL替换成我们图片的SRC属性。每一张图片都要上传。