下面的示例使用cURL上传包含为二进制文件的图像文件。
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'
工作正常。我需要从我的Java应用程序发出此请求。
我尝试了下一个代码
URL image_url = Thread.currentThread().getContextClassLoader().getResource("jobs_image.jpg");
String path = image_url.getFile();
HttpResponse<String> response = Unirest.post(uploadUrl)
.header("cache-control", "no-cache")
.header("X-Restli-Protocol-Version", "2.0.0")
.header("Authorization", "Bearer " + token + "")
.field("file", new File(path))
.asString();
但是,它返回状态400 Bad Request。 有什么方法可以从Java调用此类请求吗?
这是来自LinkedIn v2 API的请求: https://docs.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context#upload-image-binary-file
答案 0 :(得分:1)
以下方法会将图片上传到linkedIn
private void uploadMedia(String uploadUrl,String accessToken) throws IOException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer "+accessToken);
byte[] fileContents = Files.readAllBytes(new
File("path_to_local_file").toPath());
HttpEntity<byte[]> entity = new HttpEntity<>(fileContents, headers);
restTemplate.exchange(uploadUrl,HttpMethod.PUT, entity, String.class);
}
答案 1 :(得分:0)
我认为curl命令
curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....'
使用PUT
,而Java客户端使用POST
来源:curl
的手册页。
-T, --upload-file <file>
This transfers the specified local file to the remote URL. If
there is no file part in the specified URL, Curl will append the
local file name. NOTE that you must use a trailing / on the last
directory to really prove to Curl that there is no file name or
curl will think that your last directory name is the remote file
name to use. That will most likely cause the upload operation to
fail. If this is used on an HTTP(S) server, the PUT command will
be used.
不确定这是否是实际问题。您的API文档链接实际上指定了POST
。
答案 2 :(得分:0)
在将头撞到墙上几个小时之后,我终于弄清楚了如何将curl调用转换为RestClient调用(我正在使用Ruby on Rails)。
我认为您遇到的问题是必须在请求标头中将MIME类型作为Content-Type传递。
我正在使用MiniMagick来确定要上传到LinkedIn的图像的MIME类型。 MiniMagick还可以为您提供LinkedIn所需图像的二进制字符串,这是双赢的情况。
这是最终成功的呼叫:
file = MiniMagick::Image.open(FILE_PATH)
RestClient.post(UPLOAD_URL, file.to_blob, { 'Authorization': 'Bearer TOKEN', 'Content-Type': file.mime_type })