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

2019-03-16 16:07发布

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条回答
聊天终结者
2楼-- · 2019-03-16 16:49

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

查看更多
登录 后发表回答