Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

api - How to convert curl call with "-i --upload-file" into java Unirest or any other http request?

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

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

I have tried next code

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After several hours of banging my head against the wall, I finally figured out how to convert the curl call into a RestClient one (I'm using Ruby on Rails).

I think the problem you're having is that you have to pass the MIME type as the Content-Type in the request headers.

I'm using MiniMagick to figure out the MIME type of the image I'm uploading to LinkedIn. MiniMagick can also give you the binary string of the image that LinkedIn requires, so it's a win-win situation.

This is the call that finally worked:

file = MiniMagick::Image.open(FILE_PATH)
RestClient.post(UPLOAD_URL, file.to_blob, { 'Authorization': 'Bearer TOKEN', 'Content-Type': file.mime_type })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...