如何在Android上使用multipart/form-data上传图片/图片

Jos*_*eph 11 upload android facebook multipartform-data

这是我的代码.

我得到了Http 400错误,有人能帮帮我吗?

HttpClient   httpClient;
HttpPost     httpPost;
HttpResponse response;
HttpContext  localContext;
FileEntity   tmp = null;   
String       ret = null;

httpClient = new DefaultHttpClient( );
httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109) ;

httpPost = new HttpPost(url);
tmp      = new FileEntity( data,"UTF-8" );

httpPost.setEntity( tmp );
httpPost.setHeader( "Content-Type", "multipart/form-data" );
httpPost.setHeader( "access_token", facebook.getAccessToken( ) );
httpPost.setHeader( "source",       data.getAbsolutePath( ) );
httpPost.setHeader( "message",      "Caption for the photo" );

localContext = new BasicHttpContext( );
response     = httpClient.execute( httpPost,localContext );
Run Code Online (Sandbox Code Playgroud)

bobince,谢谢这是我的新ID,我会尝试将OAuth放到我的连接头.

这是我的旧代码,我会尽快更新.

private void uploadPicture( ) throws ParseException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams( ).setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );

    HttpPost httppost = new HttpPost( "https://graph.facebook.com/me/photos" );
    File file = new File( sdpicturePath );

    // DEBUG
    Log.d( "TSET", "FILE::" + file.exists( ) ); // IT IS NOT NULL
    Log.d( "TEST", "AT:" + fbAccessToken ); // I GOT SOME ACCESS TOKEN

    MultipartEntity mpEntity  = new MultipartEntity( );
    ContentBody cbFile        = new FileBody( file, "image/png" );
    ContentBody cbMessage     = new StringBody( "TEST TSET" );
    ContentBody cbAccessToken = new StringBody( fbAccessToken );

    mpEntity.addPart( "access_token", cbAccessToken );
    mpEntity.addPart( "source",       cbFile        );
    mpEntity.addPart( "message",      cbMessage     );        

    httppost.setEntity( mpEntity );

    // DEBUG
    System.out.println( "executing request " + httppost.getRequestLine( ) );
    HttpResponse response = httpclient.execute( httppost );
    HttpEntity resEntity = response.getEntity( );

    // DEBUG
    System.out.println( response.getStatusLine( ) );
    if (resEntity != null) {
      System.out.println( EntityUtils.toString( resEntity ) );
    } // end if

    if (resEntity != null) {
      resEntity.consumeContent( );
    } // end if

    httpclient.getConnectionManager( ).shutdown( );
} // end of uploadPicture( )
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 8

setEntity设置整个请求体的来源,因此只有在data文件是已编码的multipart/form-data块时才会有效.

要创建multipart/form-data用作POST请求正文的已编码表单提交,通常需要MIME多部分编码器org.apache.http.entity.mime.MultipartEntity.不幸的是,这不是由Android捆绑的,所以如果你想要它,你将不得不从Apache 引入更新的HttpClient.

请参阅此问题以获取示例代码和此主题的背景信息.