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 + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: video/mp4 \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);
            }
 
            /*對類型為video的素材進行特殊處理*/
            if ("video".equals(type)) {
                output.write(("--" + boundary + "\r\n").getBytes());
                output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
                output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}", title, introduction).getBytes());
            }
 
            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 (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,修改一下代碼就可以使用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM