微信开发,求新增永久素材接口的java调用示例

发布于 2022-01-03 13:55:02 字数 5588 浏览 763 评论 9

新增临时素材接口可以调通,但是新增永久素材接口就是调不通。实在走投无路了。



我是用这个方法调用的


public static String formUpload(String urlStr, Map<String, String> textMap,  
            Map<String, String> fileMap) {  
        String res = "";  
        HttpURLConnection conn = null;  
        String BOUNDARY = "---------------------------"+ System.currentTimeMillis(); //boundary就是request头和上传文件内容的分隔符  
        try {  
        	
            URL url = new URL(urlStr); 
            
            conn = (HttpURLConnection) url.openConnection(); 
            conn.setConnectTimeout(20000);  
            conn.setReadTimeout(30000);  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
            conn.setUseCaches(false);  
            conn.setRequestMethod("POST");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36");  
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);  

            OutputStream out = new DataOutputStream(conn.getOutputStream());  
            // text  
            if (textMap != null) {  
                StringBuffer strBuf = new StringBuffer();  
                Iterator iter = textMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    strBuf.append("rn").append("--").append(BOUNDARY).append(  
                            "rn");  
                    strBuf.append("Content-Disposition: form-data; name="" 
                            + inputName + ""rnrn");  
                    strBuf.append(inputValue);  
                }  
                out.write(strBuf.toString().getBytes("utf-8"));  
            }  
   
            // file  
            if (fileMap != null) {  
                Iterator iter = fileMap.entrySet().iterator();  
                while (iter.hasNext()) {  
                    Map.Entry entry = (Map.Entry) iter.next();  
                    String inputName = (String) entry.getKey();  
                    String inputValue = (String) entry.getValue();  
                    if (inputValue == null) {  
                        continue;  
                    }  
                    File file = new File(inputValue);  
                    String filename = file.getName();  
                    String contentType = new MimetypesFileTypeMap()  
                            .getContentType(file);  
                    if (filename.endsWith(".png")) {  
                        contentType = "image/png";  
                    }else if(filename.endsWith(".jpg")){
                    	 contentType = "image/jpeg";  
                    }else if(filename.endsWith(".mp4")){
                    	contentType = "video/mpeg4";
                    } 
                    if (contentType == null || contentType.equals("")) {  
                        contentType = "application/octet-stream";  
                    }  
   
                    StringBuffer strBuf = new StringBuffer();  
                    strBuf.append("rn").append("--").append(BOUNDARY).append("rn");  
                    strBuf.append("Content-Disposition: form-data; name="" 
                            + inputName + ""; filename="" + filename  
                            + ""rn");  
                    strBuf.append("Content-Type:" + contentType + "rnrn");  
   
                    out.write(strBuf.toString().getBytes("utf-8"));  
   
                    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[] endData = ("rn--" + BOUNDARY + "--rn").getBytes("utf-8");  
            out.write(endData);  
            out.flush();  
            out.close();  
   
            // 读取返回数据  
            StringBuffer strBuf = new StringBuffer();  
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                strBuf.append(line).append("n");  
            }  
            res = strBuf.toString();  
            reader.close();  
            reader = null;  
        } catch (Exception e) {  
            System.out.println("发送POST请求出错。" + urlStr);  
            e.printStackTrace();  
        } finally {  
            if (conn != null) {  
                conn.disconnect();  
                conn = null;  
            }  
        }  
        
        System.out.println(res);
        
        JSONObject jsonObj = JSONObject.fromObject(res);
		String mediaId = jsonObj.getString("media_id");
		return mediaId;
    }


看微信的接口文档我也是醉了,都是Php示例。这里面说要提交两个表单,到底怎么弄啊。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

如此安好 2022-01-07 19:05:20

把这个form-data; name=""+ inputName +"";改为form-data; name=""+media+"";

获取永久图片素材的接口有没有人调通,求指教

各自安好 2022-01-07 19:04:40

我后来直接在linux里使用curl命令,发现根本调不通,无解

倾城泪 2022-01-07 18:54:50

微信小白路过,帮你顶下。

网名女生简单气质 2022-01-07 17:19:23

求教,同样遇到这个问题,上传永久素材,缺少多媒体文件

明媚如初 2022-01-07 13:52:44

帮忙顶。请教下新增其他类型的永久素材时,
media参数要传些什么东西。

疾风者 2022-01-07 04:45:08

我去。。。沉了~

伴我心暖 2022-01-06 18:38:36

自己顶

韬韬不绝 2022-01-06 15:12:07

这个方法上传永久的可以,临时的有问题

乞讨 2022-01-04 08:19:26

我找到办法了

public static String postFile(String url, String filePath,
String title,String introduction) {
File file = new File(filePath);
if(!file.exists())
return null;
String result = null;
try {
URL url1 = new URL(url); 
HttpURLConnection conn = (HttpURLConnection) url1.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 + "rn").getBytes());
output.write(String.format("Content-Disposition: form-data; name="media"; filename="%s"rn", file.getName()).getBytes());  
output.write("Content-Type: video/mp4 rnrn".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);
}
output.write(("--" + boundary + "rn").getBytes());
output.write("Content-Disposition: form-data; name="description";rnrn".getBytes());
output.write(String.format("{"title":"%s", "introduction":"%s"}",title,introduction).getBytes());
output.write(("rn--" + boundary + "--rnrn").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();
System.out.println(result);
} catch (ClientAbortExceptione) {
logger.error("postFile,不支持http协议",e);
} catch (IOException e) {
logger.error("postFile数据传输失败",e);
}
logger.info("{}: result={}",url,result);
return result;
}

public static void main(String[] args) {
String url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token="
+ "U_0AIUrkfmVk0LXlaGu0lx5CXx-_4&type=video";
postFile(url, "/Users/jlusoft/Desktop/test.mp4","test","dfd");
}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文