2010-07-29 2 views
11

이것은 내 코드입니다.안드로이드에서 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

+0

안녕하세요, 어떻게이 문제를 해결 했습니까? 나는 지금 같은 문제에 직면하고있다. –

답변

8

setEntity 전체 요청 본문의 소스를 설정하므로 data 파일이 이미 부호화 multipart/form-data 블록 인 경우에만 작동한다.

multipart/form-data 인코딩 된 양식 제출을 POST 요청 본문으로 사용하려면 일반적으로 org.apache.http.entity.mime.MultipartEntity 인 MIME 다중 부품 엔코더가 필요합니다. 안타깝게도 Android에 번들로 제공되지 않으므로 원하는 경우 Apache에서 최신 HttpClient을 가져와야합니다.

예제 코드의 경우 this question을, 백그라운드의 경우 this thread을 참조하십시오.

+0

감사합니다. 나는 이제 시험에 응합니다.^___^ – Joseph

+0

쿨 !! 하지만 이제는 오류가 발생했습니다 ... >> { "error": { "type": "OAuthException", "message": "OAuth 액세스 토큰이 잘못되었습니다."}} – Joseph

+1

OAuth는 애플리케이션 수준의 문제입니다. 파일 업로드 또는 양식 작성과 관련이 있습니다. 사용자에게 권한을 부여하라는 요청과 함께 ['oauth_' 헤더] (http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/)를 전달해야하는 것처럼 들립니다. 데이터. – bobince

3

아파치 라이브러리를 포스트로 이미지를 전송하여 내 작업 솔루션이 : 페이스 북의 그래프 API에 대한 같은

  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

,이 코드는 완벽하게 작동합니다. 그러나 때때로 파일명 대신 이름을 사용해야하며 그래프 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(); 
관련 문제