1
回答
微信公众号开发,上传素材时报错,40113
华为云实践训练营,热门技术免费实践!>>>   

下面是代码,不知道哪儿错了,一步一步调试,也没找到问题:

public static String postFile(String filePath, String title,String introduction,String type){
// 获取token
String access_token=AccessTokenApi.getAccessToken().getAccessToken();
String url = FILE_URL.replace("ACCESS_TOKEN",access_token);
url = url.replace("TYPE",type);
File file = new File(filePath);
if(!file.exists())
{
   return null;
}
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";  
} 
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(String.format("Content-Type:\"%s\"\r\n\r\n",contentType).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("postFile_result==>:"+result);
}catch (IOException e) {
	LOGGER.error("postFile数据传输失败",e);
} 
        LOGGER.info("{}: result={}",url,result);
	return result;
}



举报
Joey-Z
发帖于2年前 1回/576阅
顶部