如何向微信服务器上传临时素材

来源:互联网 发布:诺基亚e72i 软件下载 编辑:程序博客网 时间:2024/06/06 15:51

今天被这个问题折腾了一天了,各种方法都试过了,走过很多弯路,最终把这条路走通了,写个博客纪念一下。

第一步,微信交互的API大家自己上网看,在此提供链接,https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1474632113_xQVCl&token=&lang=zh_CN

第二步,其实让浏览器带着一个文档去访问微信接口很简单,没有任何难度,问题是,我们不想让浏览器直接访问微信服务器,我们想让浏览器先访问我们的Controller,然后让Controller去访问微信服务器。至于为什么这么做,最重要的原因有两点,1.方便获取media_id(素材上传到微信服务器,服务器会返回一个media_id,方便调用素材),2.方便后台管理,查看发送记录等等。

第三步,话不多说,直接上代码,不懂得请看注释,或者私信我。

public void addTempMaterial(HttpServletRequest request,HttpServletResponse response) throws AppException, IOException{
        // 转型为MultipartHttpRequest:   
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
        // 获得文件  
        MultipartFile mfile = multipartRequest.getFile("mfile");   
        File file = new File(mfile.getOriginalFilename());
        FileUtils.copyInputStreamToFile(mfile.getInputStream(), file);
        //获得文件类型
        String type = mfile.getContentType();
        String filetype = type.substring(0, 5);
        if("audio".equals(filetype)){
            type="voice";
        }
        HttpClient client = new HttpClient();  
        // 返回结果集  
        JSONObject resJson = new JSONObject();  
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accessServer.getAccessToken()+"&type="+type;
        PostMethod postMethod = new PostMethod(url);  
        // FilePart:用来上传文件的类  
        FilePart filePart = new FilePart("img", file);  
        Part[] parts = { filePart };  
        // 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装  
        MultipartRequestEntity mre = new MultipartRequestEntity(parts,  
        postMethod.getParams());  
        postMethod.setRequestEntity(mre);  
        // 执行请求  
        client.executeMethod(postMethod);  
        String result = postMethod.getResponseBodyAsString();
        resJson = JSONObject.parseObject(result);
        logger.debug("返回的状态码:{}",resJson);
   }

0 0
原创粉丝点击