Twitter视频上传Java

时间:2016-07-17 15:30:37

标签: java twitter multipartform-data

我试图在Twitter上使用Java上传视频并且由于同样的原因而导致失败{“错误”:[{“code”:214,“message”:“Bad request。”}]}。

Twitter称该视频需要基于64位编码的媒体文件块。我上面的代码用于上传相同的

    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文件时遗漏了什么吗?

1 个答案:

答案 0 :(得分:0)

据我所知,一旦我们将媒体上传到media / upload.json端点,我们必须通过传递再次调用statuses / update_with_media.json端点 mediaId返回上面会将媒体发布到twitter,状态也是...请更正并建议......