Azkaban 中有一个 POST API 用于上传 zip 文件。我可以按照文档中的说明使用curl 进行上传。
curl -k -i -H "Content-Type: multipart/mixed" -X POST --form 'session.id=47cb9240-f8fe-46f9-9cba-1c1a293a0cf3' --form 'ajax=upload' --form 'file=@atest.zip;type=application/zip' --form 'project=aaaa;type=plain' http://localhost:8081/manager
http://azkaban.github.io/azkaban/docs/2.5/#api-upload-a-project-zip
但我想在 Java 中调用相同的 API。有人可以帮我如何用 Java 做到这一点吗?
最佳答案
您将需要使用Apache HttpComponents框架。
创建一个 HttpClient、一个 HttpPost 请求和一个多部分实体,然后执行该请求。 下面是一个示例:
HttpClient httpClient = HttpClientBuilder.create().setDefaultConnectionConfig(config).build();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
// add parts to your form here
builder.addPart("<param name>", <part>);
// if you need to upload a file
File uploadPkg = new File(pathToUpload);
FileBody fBody = new FileBody(uploadPkg);
builder.addPart("file", fBody);
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
希望有帮助。
关于java - 使用Java调用上传API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29554909/