我正在尝试在Spring中实现以下cURL命令的等效功能,以调用API(Twilio)来上传媒体:
curl --header 'Authorization: Basic <VALID_BASIC_AUTH_TOKEN>' --data-binary "@test.png" https://mcs.us1.twilio.com/v1/Services/<ACCOUNT_ID>/Media -v
此请求运行良好,并且生成的标头为:
> Accept: */*
> Authorization: Basic <VALID_BASIC_AUTH_TOKEN>
> Content-Length: 385884
> Content-Type: application/x-www-form-urlencoded
我在Java中的代码是:
@Repository
public class TwilioMediaRepository {
private RestTemplate client;
@Value("${twilio.chat.sid}")
private String chatSid;
@Value("${twilio.media.api.endpoint}")
private String endpoint;
@Value("${twilio.all.accountsid}")
private String accountSid;
@Value("${twilio.all.authtoken}")
private String accountSecret;
@Autowired
public TwilioMediaRepository(RestTemplate client) {
this.client = client;
}
public Media postMedia(byte[] file) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.ALL));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
client.getInterceptors().add(new RequestResponseLoggingInterceptor());
client.getInterceptors().add(new BasicAuthorizationInterceptor(accountSid, accountSecret));
HttpEntity<byte[]> entity = new HttpEntity<>(file, headers);
ResponseEntity<Media> media = this.client.postForEntity(generateUrl(), entity, Media.class);
return media.getBody();
}
private String generateUrl() {
return String.format(endpoint, chatSid);
}
}
请求的日志显示标题与cURL请求完全相同:
URI : https://mcs.us1.twilio.com/v1/Services/<ACCOUNT_ID>/Media
Method : POST
Headers : {Accept=[*/*], Content-Type=[application/x-www-form-urlencoded], Content-Length=[385884], Authorization=[Basic <VALID_BASIC_AUTH_TOKEN>]}
Request body: <bunch of unreadable bytes>
但是响应日志显示我的请求对Twilio无效:
Status code : 400
Status text : Bad Request
Headers : {Content-Type=[text/html], Date=[Wed, 08 Aug 2018 15:32:50 GMT], Server=[nginx], X-Shenanigans=[none], Content-Length=[166], Connection=[keep-alive]}
Response body: <html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
我们应该如何在Spring中发送二进制文件以符合cURL的--data-binary
属性?
我尝试发送HttpEntity<ByteArrayResource>
,HttpEntity<byte[]>
,HttpEntity<FileSystemResource>
,HttpEntity<ClassPathResource>
,但没有成功。
注意:此API不支持分段文件上传。
答案 0 :(得分:1)
问题解决了。与cURL日志显示的相反,我使用的API不需要application/x-www-form-urlencoded
内容类型。
使用文件内容类型可以解决问题(在我的情况下为image/png
)