用Java调用上传API

时间:2015-04-10 06:36:59

标签: java rest curl azkaban

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做到这一点吗?

1 个答案:

答案 0 :(得分:1)

您需要使用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()));

希望它有所帮助。