2010-07-29 176 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();