5

Tôi muốn đăng ảnh (lưu trong appengine db) lên facebook.GAE/J: Làm thế nào để tôi gửi tin nhắn Multipart MIME từ appengine tới facebook

Để kiểm tra tôi đã có những hiểu biết cơ bản xuống địa phương: Tôi đã thành công với hình thức này: (. Tôi nắm lấy access_token từ một phiên gần đây để làm công việc này)

<form action="https://graph.facebook.com/7378294228/photos?access_token=AAAAAJPBSAzcBALmz7GOLZCER7Pc2347WQIDIlIFR8e2imWUzeuCKRLrXjAqR6zjaUb4laqkLtJlQlYa7X5ZBd2aNJoLom8M7IlvHfw39QZDZD" method="POST" enctype="multipart/form-data"> 
<input type="file" name="source" id="source"/> 
<input type="text" name="message" value="mymess"/> 
<input type="Submit"/> 
</form> 

đây là những gì tôi đã cố gắng trên appengine không thành công cho đến nay:

MultipartEntity mpEntity = new MultipartEntity(); 
ContentBody cbFile = new ByteArrayBody(imageBytes, "image/jpeg", "w.jpg"); 
mpEntity.addPart("source", cbFile); 

URL url = new URL("https://graph.facebook.com/"+albumUpload.getAlbumID()+"/photos?access_token="+albumUpload.getAuthToken());     
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
connection.setDoOutput(true); 
connection.setRequestMethod("POST"); 

mpEntity.writeTo(connection.getOutputStream()); 

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
    System.err.println("http success!"); 
}else{ 
    System.err.println("http failed:"+connection.getResponseCode()); 
} 

Tôi nhận được HTTP 400 - Yêu cầu không hợp lệ.

tôi thêm này để chắc chắn rằng nó đang làm một cái gì đó:

System.out.println("mpEntity image content length: "+cbFile.getContentLength()); 
System.out.println("mpEntity content type:"+mpEntity.getContentType()); 

mà kết quả trong:

mpEntity image content length: 786145 
mpEntity content type:Content-Type: multipart/form-data; boundary=oMiJCBHGVvZmU7s3FcUGXMbyU23aX_Ow 

Các ví dụ duy nhất tôi có thể tìm thấy của việc sử dụng MultipartEntity trực tuyến đang sử dụng HttpClient của setEntity(), như vậy không áp dụng vì đây là URLFetch trong appengine.

Cảm ơn bạn đã giúp đỡ/mã.

Trả lời

10

Đã giải quyết!

tôi cần phải thêm:

connection.addRequestProperty("Content-length", mpEntity.getContentLength()+""); 
connection.addRequestProperty(mpEntity.getContentType().getName(), mpEntity.getContentType().getValue()); 

Cũng thay đổi:

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

Hy vọng điều này sẽ giúp người

+0

Cảm ơn, @abramcat. Bạn đã giúp tôi rất nhiều. Tôi mất 1,5 ngày để thử đăng nhiều phần này từ GAE. – payliu

+0

Cũng xin cảm ơn abramcat, tài liệu của bạn đã là một hỗ trợ tuyệt vời cho tôi. Rất nhiều đánh giá cao! Chỉ cần tự hỏi tại sao những thứ "cơ bản" như tải lên tệp phải phức tạp và kém tài liệu. – Hugues

+0

Bạn nên chấp nhận câu trả lời này. – Gray

Các vấn đề liên quan