• java调用微信公众平台接口(一)


    微信公众平台

    这两天在网上看了其他的方法,也调试了一些,然后自己整理了一下,方便自己学习,也方便大家使用。

    调用接口

    1、java调用上传图片接口

    public final static String IMAGE = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";    
    
    public static String uploadimg(MultipartFile file ) {
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建httppost
            String requestUrl = IMAGE.replace("ACCESS_TOKEN", access_token);//替换调access_token
            HttpPost post = new HttpPost(requestUrl);
            RequestConfig config = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(20000).build();
            post.setConfig(config);
            File f = null;
            try {
                f = new File(file.getOriginalFilename());
                inputStreamToFile(file.getInputStream(),f);
                FileUtils.copyInputStreamToFile(file.getInputStream(), f);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String name = f.getName();
            FileBody fileBody = new FileBody(f, ContentType.DEFAULT_BINARY,name);
            String filename = fileBody.getFilename();
            long contentLength = fileBody.getContentLength();
            ContentType contentType = fileBody.getContentType();
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.addPart("media", fileBody);
            // 相当于 <input type="file" class="file" name="file">,匹配@RequestParam("file")
            // .addPart()可以设置模拟浏览器<input/>的表单提交
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            String result = "";
            
            try {
                CloseableHttpResponse e = client.execute(post);
                HttpEntity resEntity = e.getEntity();
                if(entity != null) {
                    result = EntityUtils.toString(resEntity);
                    System.out.println("response content:" + result);
                }
            } catch (IOException var10) {
                System.out.println("请求解析验证码io异常    "+var10);
                //logger.error("请求解析验证码io异常",var10);
                var10.printStackTrace();
            }
            
            return result;
        }
    
    public static void inputStreamToFile(InputStream ins, File file) {
            try {
                OutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    2、新增永久图片素材

    只需要修改 requestUrl

    public final static String ADD_MATERIAL_IMAGE = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";

    3、新增永久视频素材

    public final static String ADD_MATERIAL_IMAGE = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
    
    /**
         * 上传永久素材(除 图文)
         * @param    file
         * @param    type
         * @param    title type为video时需要,其他类型设null
         * @param    introduction type为video时需要,其他类型设null
         * @return    {"media_id":MEDIA_ID,"url":URL}
         */
        public static String uploadPermanentMaterial(File file, String type, String title, String introduction) {
            String url = ADD_MATERIAL_IMAGE.replace("ACCESS_TOKEN", access_token).replace("TYPE", type);// 替换调access_token
            String result = null;
     
            try {
                URL uploadURL = new URL(url);
     
                HttpURLConnection conn = (HttpURLConnection) uploadURL.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 + "
    ").getBytes());
                output.write(String.format("Content-Disposition: form-data; name="media"; filename="%s"
    ", file.getName()).getBytes());
                output.write("Content-Type: video/mp4 
    
    ".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);
                }
     
                /*对类型为video的素材进行特殊处理*/
                if ("video".equals(type)) {
                    output.write(("--" + boundary + "
    ").getBytes());
                    output.write("Content-Disposition: form-data; name="description";
    
    ".getBytes());
                    output.write(String.format("{"title":"%s", "introduction":"%s"}", title, introduction).getBytes());
                }
     
                output.write(("
    --" + boundary + "--
    
    ").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 (IOException e) {
                //....
            }
            
            return result;
        }

    上传视频的这个方法也可以上传其他素材。

    4、上传永久图文素材

    首先考虑传值,官方的示例

    {
        "articles": [{
         "title": TITLE,
        "thumb_media_id": THUMB_MEDIA_ID,
        "author": AUTHOR,
        "digest": DIGEST,
        "show_cover_pic": SHOW_COVER_PIC(0 / 1),
        "content": CONTENT,
        "content_source_url": CONTENT_SOURCE_URL,
        "need_open_comment":1,
        "only_fans_can_comment":1
    },
        //若新增的是多图文素材,则此处应还有几段articles结构
    ]
    }

    1、直接put json,下面是一个简单的例子。这样很容易完成示例

    //{   "tag":{ "id":134,//标签id "name":"广东"   } }
    
    JSONObject json1 = new JSONObject();
            json1.put("name", "广东");
            JSONObject json = new JSONObject();
            json.put("tag", json1);

    2、使用实体类,可以参数与json转换

    /*获取素材列表参数实体类**/
    public class AddNewsParam {
        
        private Articles [] articles;
        
        public class Articles {
            private String title;// 图文消息的标题
            private String thumb_media_id;// 图文消息的封面图片素材id(必须是永久mediaID)
            private String author;// 作者
            private String digest;// 图文消息的摘要,仅有单图文消息才有摘要,多图文此处为空
            private Integer show_cover_pic;// 是否显示封面,0为false,即不显示,1为true,即显示
            private String content;// 图文消息的具体内容,支持HTML标签,必须少于2万字符,小于1M,且此处会去除JS
            private String content_source_url;// 图文消息的原文地址,即点击“阅读原文”后的URL
            private Integer need_open_comment;// 图文页的URL,或者,当获取的列表是图片素材列表时,该字段是图片的URL
            private Integer only_fans_can_comment;// Uint32 是否粉丝才可评论,0所有人可评论,1粉丝才可评论
            public String getTitle() {
                return title;
            }
            public void setTitle(String title) {
                this.title = title;
            }
            public String getThumb_media_id() {
                return thumb_media_id;
            }
            public void setThumb_media_id(String thumb_media_id) {
                this.thumb_media_id = thumb_media_id;
            }
            public String getAuthor() {
                return author;
            }
            public void setAuthor(String author) {
                this.author = author;
            }
            public String getDigest() {
                return digest;
            }
            public void setDigest(String digest) {
                this.digest = digest;
            }
            public Integer getShow_cover_pic() {
                return show_cover_pic;
            }
            public void setShow_cover_pic(Integer show_cover_pic) {
                this.show_cover_pic = show_cover_pic;
            }
            public String getContent() {
                return content;
            }
            public void setContent(String content) {
                this.content = content;
            }
            public String getContent_source_url() {
                return content_source_url;
            }
            public void setContent_source_url(String content_source_url) {
                this.content_source_url = content_source_url;
            }
            public Integer getNeed_open_comment() {
                return need_open_comment;
            }
            public void setNeed_open_comment(Integer need_open_comment) {
                this.need_open_comment = need_open_comment;
            }
            public Integer getOnly_fans_can_comment() {
                return only_fans_can_comment;
            }
            public void setOnly_fans_can_comment(Integer only_fans_can_comment) {
                this.only_fans_can_comment = only_fans_can_comment;
            }
        }
    
        public Articles[] getArticles() {
            return articles;
        }
    
        public void setArticles(Articles[] articles) {
            this.articles = articles;
        }
        
    }

    调用方法

    /**上传图文素材
         * @param accessToken
         * @return
         */
        public static String addNews(String accessToken,AddNewsParam entity) {
            String result = null;
            String requestUrl = ADD_NEWS.replace("ACCESS_TOKEN", accessToken);//替换调access_token
            String outputStr ;
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSONObject.fromObject(entity);
            outputStr = jsonObject.toString();//将参数对象转换成json字符串
            System.out.println(outputStr);
            jsonObject = httpsRequest(requestUrl, "POST", outputStr);  //发送https请求(请求的路径,方式,所携带的参数)
            // 如果请求成功  
            if (null != jsonObject) {
                try {  
                    result = jsonObject.toString();
                    System.out.println(jsonObject);
                } catch (JSONException e) {  
                    accessToken = null;  
                    // 获取Material失败  
                    result = (jsonObject.getInt("errcode")+","+jsonObject.getString("errmsg"));
                    System.out.println("jsonObject.getInt(errcode)"+jsonObject.getInt("errcode"));
                    System.out.println("jsonObject.getString(errmsg)"+jsonObject.getString("errmsg"));
                    log.error("获取Material失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));  
                }  
            }  
            return result;  
        }

    如果用第一种方式,直接传json,修改一下代码就可以使用。

  • 相关阅读:
    vuePress搭建属于自己的站点。
    webpack打包取消所有的console.log语句
    浏览器使用input复制不成功解决办法。
    腾讯地图marker中大小的控制和事件绑定。
    VUE开发公众号IOS9白屏问题
    head.s 简单分析
    linux内核初始化控制流
    一直小菜鸟在学习飞翔。
    8种主要排序算法的C#实现
    我的Jquery参考词典
  • 原文地址:https://www.cnblogs.com/zmjc/p/11493022.html
Copyright © 2020-2023  润新知