【问题标题】:Call a Upload API in Java [closed]在 Java 中调用上传 API [关闭]
【发布时间】:2015-04-10 06:36:58
【问题描述】:

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 怎么做吗?

【问题讨论】:

标签: java rest curl azkaban


【解决方案1】:

您需要使用Apache HttpComponents 框架。

创建一个HttpClient、一个HttpPost请求和一个multipart entity,然后执行Request。 下面是一个示例:

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()));

希望对你有帮助。

【讨论】:

  • 这里你使用了 Apache HttpClient,我们可以使用 Rest Libraries 实现同样的事情吗?
猜你喜欢
  • 2012-07-08
  • 2014-02-10
  • 1970-01-01
  • 2022-11-04
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多