如何使用" -i --upload-file& quot;转换curl调用到java Unirest或任何其他http请求? [英] How to convert curl call with "-i --upload-file" into java Unirest or any other http request?

查看:51
本文介绍了如何使用" -i --upload-file& quot;转换curl调用到java Unirest或任何其他http请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的示例使用cURL上传包含为二进制文件的图像文件.

The example below uses cURL to upload image file included as a binary file.

curl -i --upload-file /path/to/image.png --header "Authorization: Token" 'https://url....' 

工作正常.我需要从我的Java应用程序发出此请求.

It works fine. I need to make this request from my Java application.

我尝试了下一个代码

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调用这种请求吗?

However, it returns status 400 Bad Request. Is there any way to call such request from Java?

这是来自LinkedIn v2 API的请求:

This is a request from 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

推荐答案

以下方法会将图像上传到linkedIn

Below method will upload the image to linkedIn

参考: https://docs.microsoft.com/zh-cn/linkedin/marketing/integrations/community-management/shares/vector-asset-api#upload-the-image

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

这篇关于如何使用&quot; -i --upload-file&amp; quot;转换curl调用到java Unirest或任何其他http请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆