java调用微信公众平台接口

Posted zmjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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结构
]

 

 

 

 

代码整体没什么问题,大家导入包后可以使用。

以上是关于java调用微信公众平台接口的主要内容,如果未能解决你的问题,请参考以下文章

Java微信公众平台开发之素材管理(Spring Boot 2.X)

微信公众平台--2.获取接口调用凭据

如何调用微信js

java实现微信支付(网页版)

为啥微信公众平台的“网页授权”接口获取access

微信公众号平台开发如何与微信后台对接