DrMonkey
DrMonkey

Reputation: 21

Jetty client POST file to Jetty Server

I'm creating a Jetty client that will POST files to a Jetty Server. I'm trying to use the ContentExchange.setFileForUpload(), but I'm not able to find any example code on the web on how to use this API properly.

Upvotes: 2

Views: 1999

Answers (1)

sbordet
sbordet

Reputation: 18617

The API is self-explanatory, just pass in the file that you want to upload; the rest is just basic 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();

Look at the HttpClient documentation if you want better control on the HTTP phases the file upload will go through, or better yet switch to Jetty 9's HttpClient, which is a vastly improved implementation.

Upvotes: 4

Related Questions