无法通过Spring RestTemplate将图片上传到LinkedIn,Getting 400错误请求:[无正文]



嗨,我正试图通过Spring RestTemplate将图像上传到Linkedin,步骤如下1.初始化上传和上传url2.使用上传url将链接到服务器中的图像PUT

下面是步骤2 的方法

public String uploadImageToURL(MultipartFile file, String uploadURL) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.add("Authorization", "Bearer Redacted");
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("file", file.getBytes());
HttpEntity<MultiValueMap<String, Object>> reqEntity = new HttpEntity<>(body, headers);
try {
ResponseEntity<String> resp = new RestTemplate().exchange(uploadURL, HttpMethod.PUT, reqEntity, String.class);
} catch (HttpClientErrorException e) {
e.printStackTrace();
}
}

方法是给出-

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: [no body]

我也无法从linkedin api的文档中找出问题所在,也不清楚他们给出了一个基本的curl请求,该请求在poster上运行良好,但在编程上不起的作用

根据文件对上述方法进行卷曲

感谢您的帮助,我尝试过将标题的内容类型设置为image/png,但没有效果。

PS:我已经引用了这个链接Linkedin v2 API图像上传错误400错误请求,但它对没有帮助

您可以尝试以下操作:1-生成并打印/获取图像必须上传到的url(上传过程的第一部分(。2-尝试使用curl工具上传,就像在文档中一样。如果2有效,那么您知道前面的步骤运行良好,问题出在您发布的方法上。否则,您知道必须另谋高就(第2步之前的步骤(。

在curl工作的情况下,上传链接的服务器接受的请求可能不是HTTP(S(,而是FTP或类似的方式。在这种情况下,您需要找到该协议的解决方案。

关于您当前的实施:

  • 不鼓励使用RestTemplate,因为它很快将不再受支持
  • 改为使用WebClient:定义请求正文的链接
  • 不要使用MultiValueMap,因为它将文件添加为键值对,并且从文档上的示例判断;文件";键,就像您定义的一样

作为最后的手段,如果curl调用有效,而其他什么都不起作用,您可以创建一个简单的Bash/Shell脚本,该脚本只在流程的第2部分调用。编码快乐!:(

找到了解决方案,实际使用ByteArrayResource和正确的content-type解决了问题,这里是更新的代码

private void uploadImage(MultipartFile file, String token, String uploadURL) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
headers.add("X-Restli-Protocol-Version", "2.0.0");
headers.add("Content-Type", file.getContentType());
ByteArrayResource bytes = new ByteArrayResource(file.getBytes()) {
@Override
public String getFilename() {
return file.getName();
}
};
HttpEntity<ByteArrayResource> reqEntity = new HttpEntity<ByteArrayResource>(bytes, headers);
try {
ResponseEntity<String> imageUpload = new RestTemplate().exchange(uploadURL, HttpMethod.PUT, reqEntity, String.class);
} catch (HttpClientErrorException e) {
e.printStackTrace();
}
}

我参考了这个问题以获得真知灼见。

相关内容

最新更新