微信公众号回复图片

1.将要回复的图片上传至微信服务器成为永久素材,本人之前使用的是上传临时素材,实践久了,感觉临时素材多有不便,便决定使用永久素材的方式,下面是上传永久素材的实现办法:

	/**
	 * 上传其他永久素材(图片素材的上限为5000,其他类型为1000)
	 *
	 * @return
	 * @throws Exception
	 */
	public static JSONObject addMaterialEver(String fileurl, String type, String token) {
	    try {
	        File file = new File(fileurl);
	        //上传素材
	        String path = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + token + "&type=" + type;
	        String result = connectHttpsByPost(path, null, file);
	        result = result.replaceAll("[\\\\]", "");
	       log.info("result:" + result);
	        JSONObject resultJSON = JSONObject.fromObject(result);
	        if (resultJSON != null) {
	            if (resultJSON.get("media_id") != null) {
	               log.info("上传" + type + "永久素材成功");
	                return resultJSON;
	            } else {
	               log.info("上传" + type + "永久素材失败");
	            }
	        }
	        return null;
	    } catch (IOException e) {
	    	 log.error(e.getMessage(),e); 
	    } catch (NoSuchAlgorithmException e) {
	    	 log.error(e.getMessage(),e); 
	    } catch (NoSuchProviderException e) {
	    	 log.error(e.getMessage(),e); 
	    } catch (KeyManagementException e) {
	    	 log.error(e.getMessage(),e); 
	    }
	    return null;
	}


	public static  String connectHttpsByPost(String path, String KK, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
	    URL urlObj = new URL(path);
	    //连接
	    HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
	    String result = null;
	    con.setDoInput(true);

	    con.setDoOutput(true);

	    con.setUseCaches(false); // post方式不能使用缓存

	    // 设置请求头信息
	    con.setRequestProperty("Connection", "Keep-Alive");
	    con.setRequestProperty("Charset", "UTF-8");
	    // 设置边界
	    String BOUNDARY = "----------" + System.currentTimeMillis();
	    con.setRequestProperty("Content-Type",
	            "multipart/form-data; boundary="
	                    + BOUNDARY);

	    // 请求正文信息
	    // 第一部分:
	    StringBuilder sb = new StringBuilder();
	    sb.append("--"); // 必须多两道线
	    sb.append(BOUNDARY);
	    sb.append("\r\n");
	    sb.append("Content-Disposition: form-data;name=\"media\";filelength=\"" + file.length() + "\";filename=\""

	            + file.getName() + "\"\r\n");
	    sb.append("Content-Type:application/octet-stream\r\n\r\n");
	    byte[] head = sb.toString().getBytes("utf-8");
	    // 获得输出流
	    OutputStream out = new DataOutputStream(con.getOutputStream());
	    // 输出表头
	    out.write(head);

	    // 文件正文部分
	    // 把文件已流文件的方式 推入到url中
	    DataInputStream in = new DataInputStream(new FileInputStream(file));
	    int bytes = 0;
	    byte[] bufferOut = new byte[1024];
	    while ((bytes = in.read(bufferOut)) != -1) {
	        out.write(bufferOut, 0, bytes);
	    }
	    in.close();
	    // 结尾部分
	    byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
	    out.write(foot);
	    out.flush();
	    out.close();
	    StringBuffer buffer = new StringBuffer();
	    BufferedReader reader = null;
	    try {
	        // 定义BufferedReader输入流来读取URL的响应
	        reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
	        String line = null;
	        while ((line = reader.readLine()) != null) {
	            buffer.append(line);
	        }
	        if (result == null) {
	            result = buffer.toString();
	        }
	    } catch (IOException e) {
	       log.info("发送POST请求出现异常!" + e);
	       log.error(e.getMessage(),e); 
	    } finally {
	        if (reader != null) {
	            reader.close();
	        }
	    }
	    return result;
	}

	/**
	 * 测试上传图片至微信服务器获得media_id
	 * @param args
	 */
	public static void main(String[] args) {
	    try {
             //获得Access_token的方法,请自行百度
	        String token = Access_tokenDemo.getSavedAccess_token();
	        String path = "E:\\app.jpg";
	        JSONObject object = addMaterialEver(path,"image",token);
	        boolean b=object.containsKey("media_id");
	        if (b==true) {
				String media_id=object.getString("media_id");
				System.out.println("media_id:"+media_id);
			}
	       log.info(object.toString());
	    } catch (Exception e) {
	       log.error(e.getMessage(),e);
	    }
	}

项目运行,获得mediaId,下面是请求成功后返回的json:

{"media_id":"KpCBpHKEjL3J7gA","url":"http://mmbiz.qpic.cn/mmbiz_jpg/lfR5iby6iaKT6ibLhic1Rvp4jft70nZY5N0da4Fx27ujQ/0?wx_fmt=jpeg"}

获得media_id后,就可用来回复图片,下面是调用的过程:

	/**
	 * 使用永久素材回复图片信息
	 * 测试用 
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String returnIMGMessage(String toUserName,String fromUserName){
		String mediaId="Kphhsheut1lyAziUfJ7gA";
		String imgMsg=MessageUtil.initImageMessage(mediaId, toUserName, fromUserName);
		return imgMsg;
	}

下面附上回复图片xml的方法initImageMessage:

    /**
     * 组装图片xml
     * @MethodName:initImageMessage
     *@author:
     *@ReturnType:String
     *@param MediaId
     *@param toUserName
     *@param fromUserName
     *@return
     */
	public static String initImageMessage(String MediaId,String toUserName,String fromUserName){		
		String message = null;
		Image image=new Image();
		image.setMediaId(MediaId);
		ImageMessage imageMessage = new ImageMessage();
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setCreateTime(new Date().getTime());
		imageMessage.setImage(image);
		imageMessage.setMsgType(REQ_MESSAGE_TYPE_IMAGE);
		message = imageMessageToXml(imageMessage);
		return message;

	}
	

	/**
	 * 图片转成xml
	 * @MethodName:textMessageToXml
	 *@author:maliran
	 *@ReturnType:String
	 *@param textMessage
	 *@return
	 */
    public static String imageMessageToXml(ImageMessage imageMessage){
		  xstream.alias("xml", imageMessage.getClass());  
          return xstream.toXML(imageMessage);
    }


 
    /** 
     * 扩展xstream,使其支持CDATA块 
     *  
     * @date 2013-05-19 
     */  
    private static XStream xstream = new XStream(new XppDriver() {  
        public HierarchicalStreamWriter createWriter(Writer out) {  
            return new PrettyPrintWriter(out) {  
                // 对所有xml节点的转换都增加CDATA标记  
                boolean cdata = true;  
  
                @SuppressWarnings("unchecked")  
                public void startNode(String name, Class clazz) {  
                    super.startNode(name, clazz);  
                }  
  
                protected void writeText(QuickWriter writer, String text) {  
                    if (cdata) {  
                        writer.write("<![CDATA[");  
                        writer.write(text);  
                        writer.write("]]>");  
                    } else {  
                        writer.write(text);  
                    }  
                }  
            };  
        }  
    });  

上面initImageMessage方法中Image类为自己定义的,它只有一个属性MediaId,下边一并给出Image和ImageMessage类的代码:

@Data
public class ImageMessage extends BaseMessage {

	
 private Image Image;

}


@Data
public class Image {
	
	private String MediaId;
}

亲测可用!

发布了137 篇原创文章 · 获赞 28 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/shenxiaomo1688/article/details/100043637