File attachment with REST API - java

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

Related

How to POST NON-JSON request using Apache HttpClient?

I am to hitting an API which will return string data and as well I want to send data of string type(textfile in a paragraph).
You can use Apache httpcomponents, with http entities
Here is an example for sending a file in your POST request:
File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));
HttpPost httppost = new HttpPost("http://localhost/action.do");
httppost.setEntity(entity);
If you want a text content, you can use StringEntity:
StringEntity myEntity = new StringEntity("something", ContentType.create("text/plain", "UTF-8"));

Apache HttpPost Multiple Files upload failes with server error - Missing initial multi part boundary

I try to upload multiple files, using Apache Http library.
compile group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.5.6'
This is how I upload files.
String url = "url";
File f1 = new File("file1");
File f2 = new File("file2");
HttpPost request = new HttpPost(url);
request.addHeader("Content-Type", "multipart/form-data");
request.addHeader("Authorization", "Basic abcd=");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody1 = new FileBody(f1, ContentType.DEFAULT_TEXT);
FileBody fileBody2 = new FileBody(f2, ContentType.DEFAULT_TEXT);
multipartEntityBuilder.addPart("file_1_param", fileBody1);
multipartEntityBuilder.addPart("file_2_param", fileBody2);
HttpEntity httpEntity = multipartEntityBuilder.build();
request.setEntity(httpEntity);
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
InputStream is = entity.getContent();
String textResponse = InputStreamUtils.readText(is);
System.out.println(textResponse);
It prints.
<pre> Server Error</pre></p><h3>Caused by:</h3><pre>java.lang.RuntimeException: javax.servlet.ServletException: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: Missing initial multi part boundary
at com.ca.devtest.acl.servlet.filters.RemoteAuthenticationFilter.doFilter(RemoteAuthenticationFilter.java:285)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1676)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:101)
It works if I upload only one file though!
Note, this is not a duplicate. These links show posts which refer the problem on the server side. This problem is with the client side.
Jetty throws "Missing content for multipart request" on multipart form request
500 Internal server error Android HttpPost file upload
I found out a resolution. I wanted to share it with other people, so you can 1) learn how to upload files and 2) pay attention to HTTP headers.
When I append FileBody to MultipartEntityBuilder it automatically sets boundary. I simply removed this line from the code
request.addHeader("Content-Type", "multipart/form-data"); //Remove it
Example of a POST request with one or more files attached
The Multipart Content-Type
Remove the content-type option from the headers completely to make it work.
Example
headers = {
'cache-control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
'postman-token': '26ef68f6-e579-a029-aec2-09b291678b4d',
'storeid': '4223556'
}

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.

Apache HttpClient making multipart form post

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

Categories

Resources