abr*_*cat 5 java google-app-engine multipartform-data facebook-graph-api
我想将一张照片(存储在appengine db中)发布到facebook.
为了测试我已经在本地获得了基本的理解:我已经成功使用这种形式:
<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>
Run Code Online (Sandbox Code Playgroud)
(我抓住了最近一次会话中的access_token来完成这项工作.)
这是迄今为止我尝试过的关于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());
}
Run Code Online (Sandbox Code Playgroud)
我收到HTTP 400 - 错误请求.
我添加了这些以确保它正在做某事:
System.out.println("mpEntity image content length: "+cbFile.getContentLength());
System.out.println("mpEntity content type:"+mpEntity.getContentType());
Run Code Online (Sandbox Code Playgroud)
这导致:
mpEntity image content length: 786145
mpEntity content type:Content-Type: multipart/form-data; boundary=oMiJCBHGVvZmU7s3FcUGXMbyU23aX_Ow
Run Code Online (Sandbox Code Playgroud)
我在网上找到MultipartEntity用法的唯一例子是使用HttpClient的setEntity(),因为这不适用,因为这是一个appengine下的URLFetch.
感谢您的帮助/代码.
abr*_*cat 10
解决了!
我需要补充一下:
connection.addRequestProperty("Content-length", mpEntity.getContentLength()+"");
connection.addRequestProperty(mpEntity.getContentType().getName(), mpEntity.getContentType().getValue());
Run Code Online (Sandbox Code Playgroud)
也改变了:
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Run Code Online (Sandbox Code Playgroud)
希望这有助于某人