Jetty客户端POST文件到Jetty Server

时间:2013-04-14 12:22:07

标签: jetty

我正在创建一个将文件POST到Jetty服务器的Jetty客户端。我正在尝试使用ContentExchange.setFileForUpload(),但我无法在网上找到有关如何正确使用此API的任何示例代码。

1 个答案:

答案 0 :(得分:4)

API不言自明,只需传入您要上传的文件;其余的只是基本的HTTP:

HttpClient httpClient = ...;

File file = ...;

ContentExchange exchange = new ContentExchange(true);
exchange.setURL("http://host/path");
exchange.setMethod(HttpMethods.POST);
exchange.setFileForUpload(file);
exchange.setRequestHeader("Content-Type", "application/octet-stream");
exchange.setRequestHeader("Content-Length", String.valueOf(file.length()));
httpClient.send(exchange);

// Wait for the upload to complete
exchange.waitForDone();

如果您希望更好地控制文件上传将要经历的HTTP阶段,请查看HttpClient documentation,或者更好地切换到Jetty 9's HttpClient,这是vastly improved实施。