【发布时间】:2015-07-26 15:30:23
【问题描述】:
我想使用 Spring 的 RestTemplate 将 jar 上传到 nexus。我找到了有关如何使用 curl here 进行操作的说明,效果很好。但是,我完全无法将其转换为 RestTemplate 调用。这是我的代码:
String auth = "admin:admin123";
byte[] encodedAuth = Base64.encodeBase64( auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
RestTemplate restTemplate = new RestTemplate();
LinkedMultiValueMap<String, Object> files = new LinkedMultiValueMap<>();
files.add("r", "releases");
files.add("hasPom", "false");
files.add("e", "jar");
files.add("g", "com.test.proj");
files.add("a", "my-artifact");
files.add("v", "1.0.0");
files.add("p", "jar");
files.add("file", new ByteArrayResource(jarBytes));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.set("Authorization", authHeader);
HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(files, headers);
String response = restTemplate.postForObject("http://localhost:8081/nexus/service/local/artifact/maven/content", entity, String.class);
这会失败并显示400 Bad Request。查看the source 后,我的文件似乎未通过此密钥检查:
for (FileItem fi : files) {
if (fi.isFormField()) {
// parameters are first in "nibble"
processFormField(request, uploadContext, fi);
}
else {
// a file, this means NO parameters will income anymore
// we either received all the GAVs as params, or we have a POM to work with (file1)
...
FileItem.isFormField 来自 Apache Commons FileUpload。 有谁知道我如何通过我传入的“文件”来成功完成这项工作?
在另一个问题 (FileUpload isFormField() returning true when submitting file) 中,答案表明我需要一个名称字段,或者在我的情况下,“类型”没有通过。 如果是这种情况,是否可以在发出发布请求时指定这些?
【问题讨论】:
标签: spring nexus resttemplate apache-commons-fileupload