palcan
palcan

Reputation: 73

How to do multipart/form-data post in Jetty HttpClient

I'm wondering if someone could help me out there. For Java project I want to use the Jetty HttpClient that will send data to a Restful webservice. Have a few questions:

  1. Does Jetty client support multipart/form-data post? From Jetty doc, to send any data you need to specify the request content by using HttpExchange.setRequestContent(Buffer) Or HttpExchangge.setRequestContentSource(InputStream) method. If I go with setRequestContentSource for file uploading how could I set an additional form params like filename for multipart post?

  2. Is there any way to check a progress of upload using Jetty client? I need a standard thing like a progress bar that shows bytes send, %, etc Jetty provides a plenty of callbacks like onResponseContent, onResponseStatus, onRequestCommitted, but no one of them could help in monitoring how many bytes have been sent. Is it possible to get an upload progress with Jetty httpclient?

Thank you in advance

Upvotes: 1

Views: 4943

Answers (2)

Ernesto Campohermoso
Ernesto Campohermoso

Reputation: 7371

You must use MultiPartContentProvider

From: http://download.eclipse.org/jetty/9.3.9.v20160517/apidocs/org/eclipse/jetty/client/util/MultiPartContentProvider.html

A ContentProvider for form uploads with the "multipart/form-data" content type.

Example usage:

 MultiPartContentProvider multiPart = new MultiPartContentProvider();
 multiPart.addFieldPart("field", new StringContentProvider("foo"), null);
 multiPart.addFilePart("icon", "img.png", new PathContentProvider(Paths.get("/tmp/img.png")), null);
 multiPart.close();
 ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
     .method(HttpMethod.POST)
     .content(multiPart)
     .send();

The above example would be the equivalent of submitting this form:

 <form method="POST" enctype="multipart/form-data"  accept-charset="UTF-8">
     <input type="text" name="field" value="foo" />
     <input type="file" name="icon" />
 </form>

Upvotes: 4

Leo Liang
Leo Liang

Reputation: 55

Use Apache Http client 4.x would help you a bit. Please see: http://hc.apache.org/httpcomponents-client-ga/examples.html

Upvotes: -3

Related Questions