2010-07-29 35 views
11

Đây là mã của tôi.Cách sử dụng hình ảnh/hình ảnh tải lên nhiều phần/hình thức dữ liệu trên Android

Tôi gặp lỗi http 400, ai đó có thể giúp tôi không?

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, nhờ đây là id mới của tôi, tôi sẽ cố gắng đưa OAuth để tiêu đề kết nối của tôi.

Và đây là mã cũ của tôi, tôi sẽ sớm cập nhật mã đó.

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

một số cơ thể giúp tôi ... – Joseph

+0

Xin chào, bạn giải quyết vấn đề này như thế nào? Tôi đang đối mặt với cùng một vấn đề bây giờ. –

Trả lời

8

setEntity bộ nguồn của cơ thể yêu cầu toàn bộ, vì vậy đây sẽ chỉ làm việc nếu các tập tin data là một đã mã hóa multipart/form-data khối.

Để tạo một biểu mẫu được gửi mã multipart/form-data để sử dụng làm cơ quan yêu cầu POST, bạn sẽ cần bộ mã hóa đa MIME, thường là org.apache.http.entity.mime.MultipartEntity. Thật không may, điều này không được đóng gói bởi Android vì vậy nếu bạn muốn nó, bạn sẽ phải kéo một mới hơn HttpClient từ Apache.

Xem this question ví dụ mã và this thread cho nền.

+0

Cảm ơn rất nhiều, tôi đang thử ngay bây giờ.^___^ – Joseph

+0

Tuyệt vời !! nhưng giờ tôi gặp lỗi này ... >> {"lỗi": {"type": "OAuthException", "message": "Mã thông báo truy cập OAuth không hợp lệ."}} – Joseph

+1

OAuth là sự cố ở cấp ứng dụng, không phải bất kỳ điều gì để thực hiện với việc tải lên tệp hoặc tạo biểu mẫu. Có vẻ như bạn cần chuyển [tiêu đề oauth_'] (http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iv-signing-requests/) với yêu cầu cấp quyền truy cập cho người dùng dữ liệu. – bobince

3

Có giải pháp làm việc của tôi để gửi hình ảnh với bưu điện, sử dụng thư viện http apache:

  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

như đối với facebook graph api, mã này hoạt động hoàn hảo. Tuy nhiên, đôi khi, bạn cần sử dụng tên thay vì tên tệp, biểu đồ api có vẻ xung đột với tài liệu 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(); 
Các vấn đề liên quan