【发布时间】:2017-04-13 22:02:06
【问题描述】:
我尝试在 Twitter 上使用 Java 上传视频,但由于相同的原因 {"errors":[{"code":214,"message":"Bad request."}]} 一直失败。
Twitter 表示视频需要使用 base64 编码的媒体文件块。我下面的代码用于上传相同的
String url = "https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id="+mediaId+"&segment_index=0";
CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.consumerKey, this.consumerSecret);
consumer.setTokenWithSecret(token,tokenSecret);
HttpPost request = new HttpPost(url);
request.setHeader("content-type", "multipart/form-data");
MultipartEntity multiPartEntity = new MultipartEntity () ;
/*
multiPartEntity.addPart("command", new StringBody("APPEND")) ;
multiPartEntity.addPart("media_id", new StringBody(mediaId)) ;
*/
//FileBody fileBody = new FileBody(file) ;
byte[] file64 = loadFileAsBytesArray(file);
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(file64), file.getName());
multiPartEntity.addPart("media_data", cd);
/*
multiPartEntity.addPart("media_data", cd) ;
multiPartEntity.addPart("segment_index", new StringBody("0") ) ;
*/
request.setEntity(multiPartEntity);
consumer.sign(request);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
int code = response.getStatusLine().getStatusCode();
System.err.println("Code "+code);
public static byte[] loadFileAsBytesArray(File file) throws Exception
{
int length = (int) file.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
byte[] bytes = new byte[length];
reader.read(bytes, 0, length);
reader.close();
return bytes;
}
我能够获取媒体 ID,所以如果可以,请确保授权。我在上传 base 64 文件时遗漏了什么吗?
【问题讨论】:
标签: java twitter multipartform-data