5

我想发布一张照片(存储在appengine db)到facebook。GAE/J:如何从appengine发布多部分MIME邮件到facebook

为了测试我已经得到了基本的了解下当地:我已经成功这种形式:(我抓住了从的access_token最近会话,使这项工作)

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

这是我已经试过AppEngine上失败至今:

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

我得到一个HTTP 400 - 错误的请求。

我说这些,以确保它在做什么:

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

导致:

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

唯一的例子我能找到MultipartEntity使用的在线使用的HttpClient的setEntity()因为这是不适用的,因为这是在appengine下的URLFetch。

感谢您的任何帮助/代码。

回答

10

解决!

我需要添加:

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

也发生了变化:

MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

希望这可以帮助别人

+0

谢谢,@abramcat。你给了我很大的帮助。我花了1.5天的时间尝试从GAE发布多部分内容。 – payliu

+0

也感谢abramcat,你的文档对我来说是一个很好的支持。非常感谢 !只是想知道为什么诸如文件上传之类的“基本”事情必须如此复杂且记录不完整。 – Hugues

+0

你应该接受这个答案。 – Gray

相关问题