【问题标题】:How use multipart/form-data upload picture/image on Android如何在 Android 上使用 multipart/form-data 上传图片/图像
【发布时间】:2011-03-22 14:48:09
【问题描述】:

这是我的代码。

我收到 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 );

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( )

【问题讨论】:

  • 嗨,你是怎么解决这个问题的?我现在面临同样的问题。

标签: android facebook upload multipartform-data


【解决方案1】:

至于 facebook graph api,此代码完美运行。 但是,有时,您需要使用 name 而不是 filename,graph api 似乎与 rfc 文档冲突。

final String BOUNDERY = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
final String CRLF = "\r\n";
StringBuilder sbBody_1 = new StringBuilder();
sbBody_1.append("--" + BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; filename=\"source\"" + CRLF);
sbBody_1.append(CRLF);
StringBuilder sbBody_2 = new StringBuilder();
sbBody_2.append(CRLF + "--" + BOUNDERY + "--");
URL url = new URL("https://graph.facebook.com/me/photos?access_token=" + accessToken);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDERY);
connection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(sbBody_1.toString().getBytes());
out.write(bFile);// bFile is byte array of the bitmap
out.write(sbBody_2.toString().getBytes());
out.close();
BufferedReader bips = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String temp = null;
while ((temp = bips.readLine()) != null) {
    Log.d("fbnb", temp);
}
bips.close();
connection.disconnect();

【讨论】:

    【解决方案2】:

    我的工作解决方案是使用 apache http 库发送带有帖子的图像:

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
    
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);
    
                String boundary = "-------------" + System.currentTimeMillis();
    
                httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
    
                ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
                StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
                StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);
    
                HttpEntity entity = MultipartEntityBuilder.create()
                        .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                        .setBoundary(boundary)
                        .addPart("group", sbGroup)
                        .addPart("owner", sbOwner)
                        .addPart("image", bab)
                        .build();
    
                httpPost.setEntity(entity);
    
                try {
                    HttpResponse response = httpclient.execute(httpPost);
                    ...then reading response
    

    【讨论】:

      【解决方案3】:

      setEntity 设置整个请求正文的来源,因此这仅在 data 文件是已编码的 multipart/form-data 块时才有效。

      要创建 multipart/form-data 编码的表单提交以用作 POST 请求正文,您需要一个 MIME 多部分编码器,通常是 org.apache.http.entity.mime.MultipartEntity。不幸的是,这不是 Android 捆绑的,所以如果你想要它,你必须从 Apache 中获取一个更新的 HttpClient

      示例代码见this question,背景见this thread

      【讨论】:

      • 酷!但现在我得到了错误... >> {"error":{"type":"OAuthException","message":"Invalid OAuth access token."}}
      • OAuth 是应用程序级别的问题,与文件上传或表单创建无关。听起来您需要通过 oauth_ headers 请求授权访问用户数据。
      • 我在 facebook 应用程序信息页面上对 OAuth 进行了罚款。非常感谢。
      • 我正在尝试在 facebook 上上传视频.. 希望您能帮助我使用多部分请求上传视频..
      • MultipartEntity 现在已弃用,请使用 MultipartEntityBuilder.create() .addBinaryBody("file", file, ContentType.create("image/jpeg"), file.getName()).build();
      猜你喜欢
      • 2015-10-11
      • 2020-12-31
      • 2019-08-12
      • 1970-01-01
      • 2022-07-29
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2011-04-22
      相关资源
      最近更新 更多