以下是从Facebook Docs到将文件上传到服务器以发送给指定用户的卷曲:
curl \
-F recipient='{"id":"USER_ID"}' \
-F message='{"attachment":{"type":"file", "payload":{}}}' \
-F filedata=@/tmp/receipt.pdf \
"https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
curl \
-F 'recipient={"id":"USER_ID"}' \
-F 'message={"attachment":{"type":"audio", "payload":{}}}' \
-F 'filedata=@/tmp/clip.mp3;type=audio/mp3' \
"https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"
我可以通过Curl做到这一点,但我想用Java和Spring-Boot做到这一点。 怎么去呢?
我要发送的文件位于我的src-main-resource-docs文件夹中。
修改1 我想知道这个filedata = @ / tmp / clip.mp3; type = audio / MP3 这应该只是我的资源文件的链接吗?
或者我是否必须将其更改为MultipartFile才能发送?
编辑2 目前这就是我在做的事情:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("recipient", "{"id":"USER_ID"}", ContentType.APPLICATION_JSON);
File f = new File("./src/main/resources/docs/test.pdf");
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
这适用于pdfs
但是在audio / mp3中有一个type = audio / mp3。我把它放在哪里?
答案 0 :(得分:1)
最后能够通过发送Api参考将文档/媒体上传到Facebook,这就是我所做的:
我使用 OkHttp3 库来构建请求,
/*
*For Pdf ->MediaType.parse("file/pdf")
*For Video-> MediaType.parse("video/mp4")
*For Image-> MediaType.parse("image/png")
*/
final MediaType MEDIA_TYPE_PNG=MediaType.parse("audio/mp3");
final OkHttpClient client =new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("filedata", "file_name.extension", RequestBody.create(MEDIA_TYPE_PNG, new File("path_of_file")))
.addFormDataPart("recipient","{\"id\":\"USER_ID\"}")
.addFormDataPart("message", "{\"attachment\":{\"type\":\"TYPE_OF_FILE\", \"payload\":{}}}")//as in Facebook Docs
.build();
Request request = new Request.Builder()
.url("https://graph.facebook.com/v2.6/me/messages?access_token=ACCESS_TOKEN")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
需要为 IOException
添加异常处理答案 1 :(得分:0)
查看restFb库。有了它,你将能够做到:
String fileName = YOUR_FILE_NAME;
byte[] fileBytes = multipartFile.getBytes(); // could be from MultipartFile, for exaple file upload from browser
String fileType = "text/csv";
BinaryAttachment binaryAttachment = BinaryAttachment.with("file", fileName, fileBytes, fileType);
// FacebookClient from the library, look in the library docs how to use it;
// also there are several overloaded publish methods you can use
facebookClient.publish(endpoint, String.class, binaryAttachment);