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

苏文 发布于 2015/03/26 10:28
阅读 16K+
收藏 1

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



我是用这个方法调用的


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("\r\n").append("--").append(BOUNDARY).append(  
                            "\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" 
                            + inputName + "\"\r\n\r\n");  
                    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("\r\n").append("--").append(BOUNDARY).append("\r\n");  
                    strBuf.append("Content-Disposition: form-data; name=\"" 
                            + inputName + "\"; filename=\"" + filename  
                            + "\"\r\n");  
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");  
   
                    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 = ("\r\n--" + BOUNDARY + "--\r\n").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示例。这里面说要提交两个表单,到底怎么弄啊。

加载中
1
张睿知
张睿知

我找到办法了

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 + "\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);
}
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();
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");
}



p
px_wu
这个方法上传永久的可以,临时的有问题
0
苏文
苏文

自己顶

0
苏文
苏文
我去。。。沉了~
0
uknow8692
uknow8692
帮忙顶。请教下新增其他类型的永久素材时,media参数要传些什么东西。
0
j
javaHP
求教,同样遇到这个问题,上传永久素材,缺少多媒体文件
0
j
javaHP
有解决方案麻烦联系下QQ379475355
0
jfyang_2014
jfyang_2014
微信小白路过,帮你顶下。
0
暴徒
暴徒
帮顶,顺便说一下微信整这破接口真TM操蛋
0
j
javaHP

这接口太tmd纠结了,我心里骂了无数次 开发组。。。

苏文
苏文
我后来直接在linux里使用curl命令,发现根本调不通,无解
0
桂小太

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

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

返回顶部
顶部