2010-07-29 248 views
11

這是我的代碼。如何在Android上使用multipart/form-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); 

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

有些身體可以幫助我.... – Joseph 2010-07-29 10:38:29

+0

嗨,你是如何解決這個問題的?我現在面臨同樣的問題。 – 2014-02-04 22:36:51

回答

8

setEntity設置整個請求體的來源,因此,如果data文件是已經編碼完成的塊multipart/form-data這隻會工作。

要創建multipart/form-data經過編碼的表單提交以用作POST請求正文,您需要一個MIME多部分編碼器,通常爲org.apache.http.entity.mime.MultipartEntity。不幸的是,這並不是Android捆綁在一起的,所以如果你需要的話,你必須從Apache中提取一個更新的HttpClient

參見this question例如代碼和this thread爲背景。

+0

非常感謝,我現在就試試。^___^ – Joseph 2010-07-30 05:32:10

+0

酷!但現在我得到了錯誤...... >> {「error」:{「type」:「OAuthException」,「message」:「無效的OAuth訪問令牌。」}} – Joseph 2010-07-30 06:07:38

+1

OAuth是一個應用程序級別的問題,與文件上傳或表單創建有關。聽起來像你需要傳遞['oauth_'頭部](http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/)與授權訪問用戶的請求數據。 – bobince 2010-07-30 10:12:25

3

有與郵寄的圖像,使用的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 
1

爲Facebook的圖形API,此代碼的工作完美。 然而,有時候,你需要使用,而不是,圖形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();