GAE/J: How do I POST a Multipart MIME message from appengine to facebook

冷暖自知 提交于 2019-12-03 13:38:29

问题


I want to post a photo (stored in appengine db) to facebook.

To test I've got the basic understanding down locally: I've been successful with this form:

<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>

(I grabbed the access_token from a recent session to make this work.)

Here's what I've tried on appengine unsuccessfully so far:

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());
}

I get a HTTP 400 - Bad Request.

I added these to make sure it was doing something:

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

which results in:

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

The only examples I can find of MultipartEntity usage online are using HttpClient's setEntity(), as as such don't apply as this is a URLFetch under appengine.

Thanks for any help/code.


回答1:


Solved!

I needed to add:

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

Also changed:

MultipartEntity mpEntity  = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

Hope this helps someone



来源:https://stackoverflow.com/questions/8025689/gae-j-how-do-i-post-a-multipart-mime-message-from-appengine-to-facebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!