Apache HttpClient making multipart form post - java

I'm pretty green to HttpClient and I'm finding the lack of (and or blatantly incorrect) documentation extremely frustrating. I'm trying to implement the following post (listed below) with Apache Http Client, but have no idea how to actually do it. I'm going to bury myself in documentation for the next week, but perhaps more experienced HttpClient coders could get me an answer sooner.
Post:
Content-Type: multipart/form-data; boundary=---------------------------1294919323195
Content-Length: 502
-----------------------------1294919323195
Content-Disposition: form-data; name="number"
5555555555
-----------------------------1294919323195
Content-Disposition: form-data; name="clip"
rickroll
-----------------------------1294919323195
Content-Disposition: form-data; name="upload_file"; filename=""
Content-Type: application/octet-stream
-----------------------------1294919323195
Content-Disposition: form-data; name="tos"
agree
-----------------------------1294919323195--

Use MultipartEntityBuilder from the HttpMime library to perform the request you want.
In my project I do that this way:
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("number", "5555555555")
.addTextBody("clip", "rickroll")
.addBinaryBody("upload_file", new File(filePath), ContentType.APPLICATION_OCTET_STREAM, "filename")
.addTextBody("tos", "agree")
.build();
HttpPost httpPost = new HttpPost("http://some-web-site");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity result = response.getEntity();
Hope this will help.
(Updated this post to use MultipartEntityBuilder instead of deprecated MultipartEntity, using #mtomy code as the example)

MultipartEntity now shows up as deprecated. I am using apache
httpclient 4.3.3 - does anyone know what we are supposed to use
instead? I find the google searches to be so full of MultipartEntity
examples I can't find anything. – vextorspace Mar 31 '14 at 20:36
Here is the sample code in HttpClient 4.3.x
http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java
import org.apache.http.entity.mime.MultipartEntityBuilder;
HttpPost httppost = new HttpPost("http://localhost:8080" +
"/servlets-examples/servlet/RequestInfoExample");
FileBody bin = new FileBody(new File(args[0]));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
To use the class MultipartEntityBuilder, you need httpmime, which is a sub project of HttpClient
HttpClient 4.3.x:
http://hc.apache.org/httpcomponents-client-4.3.x/index.html
httpmime 4.3.x:
http://hc.apache.org/httpcomponents-client-4.3.x/httpmime/dependency-info.html

if use org.apache.commons.httpclient.HttpClient package, maybe that can help you!
HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
//here should set HttpConnectionManagerParams but not important for you
HttpClient httpClient = new HttpClient(httpConnectionManager);
PostMethod postMethod = new PostMethod("http://localhost/media");
FilePart filePart = new FilePart("file", new File(filepath));
StringPart typePart = new StringPart("type", fileContent.getType(), "utf-8");
StringPart fileNamePart = new StringPart("fileName", fileContent.getFileName(), "utf-8");
StringPart timestampPart = new StringPart("timestamp", ""+fileContent.getTimestamp(),"utf-8");
Part[] parts = { typePart, fileNamePart, timestampPart, filePart };
MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(multipartRequestEntity);
httpClient.executeMethod(postMethod);
String responseStr = postMethod.getResponseBodyAsString();

Related

File attachment with REST API

The below code is working fine to attach file in JIRA, only one problem is here
I can't use MultipartEntityBuilder as it needed to add new dependency in pom and that is not permissible , can any one please suggest which basic API I can use there? thanks in advance
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://xxxx.zzzz.net/rest/api/2/issue/" + issueID +"/attachments");
postRequest.setHeader("Authorization", "Basic <AUTHSTRING>");
postRequest.setHeader("X-Atlassian-Token", "nocheck");
File file = new File("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
URL url = new URL("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
MultipartEntityBuilder builder = MultipartBodyBuilder.create();
// This attaches the file to the POST:
builder.addBinaryBody(
"file",
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName()
);
HttpEntity multipart = builder.build();
postRequest.setEntity(multipart);
HttpResponse response = httpClient.execute(postRequest);
org.apache.http.entity.mime.MultipartEntity is deprecated as a result you'll have to use MultipartEntityBuilder.
For more related post please see this thread

MultipartEntityBuilder HttpPost socket write error in java

I am trying file upload with httpPost request (by MultipartEntityBuilder) in java. But i get a Software caused connection abort: socket write error.
Here is my httpPost body (in wireShark)
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="csrf_token"
csrf:sjwzV6dOZaNFwc0jWVrNNcFvhM7uv3BK00vZ0hCgEUzi2cG7r7Arx0Q3UZKlXeaR
------WebKitFormBoundaryWphJNFngxYSpEvNO
Content-Disposition: form-data; name="imagefilename"; filename="myfile.bin"
Content-Type: application/octet-stream
²qz‹ÁOOõMÓâg‘Ç`:----This area is file's binary code------Êëá‡/oåup
code side is:
File file = new File(filePath);
String message = csrf_token;
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("imagefilename", file, ContentType.DEFAULT_BINARY, file.getName());
builder.addTextBody("csrf_token", message, ContentType.DEFAULT_BINARY);
//
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
and error:
Is there any idea? thanks for all.
i resolved the problem, thesee links are useful for answer
here is fileupload with http Client example
here is fileupload too, with httpUrlConnection

use org.apache.http.entity.mime to upload a file to server but can't open it

I use below code to upload a text file to server and it can work.
`HttpPost httppost = new HttpPost(uri+"/uploads.xml");
MultipartEntity mpEntity = new MultipartEntity();
FileBody cbFile = new FileBody(file);
//insertValue
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1);
httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);
httppost.setHeader("Content-Type", "application/octet-stream");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
//execute
HttpResponse response = httpclient.execute(httppost);`
But when I download the text file from server, I could not open it and find that other messages(the bold text ) be added in the text file.
--RzBVXI2AHuDiIU5UHz-A1jZrpEg6a0JY
Content-Disposition: form-data; name="userfile"; filename="test.txt"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
CONTENT...
--RzBVXI2AHuDiIU5UHz-A1jZrpEg6a0JY--
THANKS!
Finally I resolved it.
I use this code
FileEntity entity = new FileEntity(file)
to replace:
FileBody cbFile = new FileBody(file);mpEntity.addPart("userfile", cbFile);
and it works.
But I don't know why....

Post text and files in Java/Android in UTF-8

I have the following code for posting a text and a file with http:
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("field_1", new StringBody(textField));
entity.addPart("field_2", new FileBody(new File(filepath)));
post.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(post);
It works nice the problem is that I need the textField value to be encoded in UTF-8.Any ideas?
Editted: Found an error in the code, posting the working answer
The sollution is to use:
new StringBody(textField,"text/plain",Charset.forName("UTF-8")

InputStreamBody in HttpMime 4.0.3 settings for content-length

I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);
MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
I'm the author of the ByteArrayBody class you have commented out.
I wrote it because I faced the same issue you did. The original Jira ticket is here: https://issues.apache.org/jira/browse/HTTPCLIENT-1014
So, since you already have a byte[], either upgrade HttpMime to the latest version, 4.1-beta1, which includes this class. Or copy the code from the Jira issue into your own project.
The ByteArrayBody class will do exactly what you need.

Categories

Resources