Apache Http Client 4 Form Post Multi-part data - java

I need to post some form parameters to a server through an HTTP request (one of which is a file). So I use Apache HTTP Client like so...
HttpPost httpPost = new HttpPost(urlStr);
params = []
params.add(new BasicNameValuePair("username", "bond"));
params.add(new BasicNameValuePair("password", "vesper"));
params.add(new BasicNameValuePair("file", payload));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-type", "multipart/form-data");
CloseableHttpResponse response = httpclient.execute(httpPost);
The server returns an error, stack trace is..
the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:954)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
I understand from other posts that I need to somehow come up with a boundary, which is a string not found in the content. But how do I create this boundary in the code I have above? Should it be another parameter? Just a code sample is what I need.

As the exception says, you have not specified the "multipart boundary". This is a string that acts as a separator between the different parts in the request. But in you case it seems like you do not handle any different parts.
What you probably want to use is MultipartEntityBuilder so you don't have to worry about how it all works under the hood.
It should be Ok to do the following
HttpPost httpPost = new HttpPost(urlStr);
File payload = new File("/Users/CasinoRoyaleBank");
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("file", payload)
.addTextBody("username", "bond")
.addTextBody("password", "vesper")
.build();
httpPost.setEntity(entity);
However, here is a version that should be compatible with #AbuMariam findings below but without the use of deprecated methods/constructors.
File payload = new File("/Users/CasinoRoyaleBank");
ContentType plainAsciiContentType = ContentType.create("text/plain", Consts.ASCII);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(payload))
.addPart("username", new StringBody("bond", plainAsciiContentType))
.addPart("password", new StringBody("vesper", plainAsciiContentType))
.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
The UrlEncodedFormEntity is normally not used for multipart, and it defaults to content-type application/x-www-form-urlencoded

I accepted gustf's answer because it got rid of the exception I was having and so I thought I was on the right track, but it was not complete. The below is what I did to finally get it to work...
File payload = new File("/Users/CasinoRoyaleBank")
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(payload))
entity.addPart( "username", new StringBody("bond"))
entity.addPart( "password", new StringBody("vesper"))
httpPost.setEntity( entity );
CloseableHttpResponse response = httpclient.execute(httpPost);

Related

How to get JSON data from solar winds Orion rest API using java

I want to get the JSON data from solarwinds orion rest api and have to write those JSON data in excel file.
I'm assuming you need a java program to send a post request to an API endpoint. ApacheHTTP library to the rescue. You can read more from the documentation here. Even more information in the official apache website
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// do something useful
}
}
Taken from this answer

Convert String (Json) to Rest Assured Response

I have a JSON body as Java String. I would like to convert this String to RestAssured Response. Is this possible?
Or
Is it possible to convert apache HttpResponse to RestAssured Response
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(body);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
I'd like to convert httpResponse to RestAssured Response
The Response Javadoc says "The response of a request made by REST Assured.". So, no I don't think its possible. I would make the request with RestAssurred anyway, I find it easier.
Reference: http://static.javadoc.io/com.jayway.restassured/rest-assured/1.2.3/com/jayway/restassured/response/Response.html

HttpPost arguments posted to server returns HTTP 500 error

I'm trying to send the equivalent of the curl '-F' option to a designated URL.
This is what the command looks like using Curl:
curl -F"optionName=cool" -F"file=#myFile" http://myurl.com
I believe I am correct in using the HttpPost class in the Apache httpcomponents library.
I supply a name=value type of parameter. The optionName is simply a string and the 'file' is a file I have stored locally on my drive (hence the #myFile to indicate its a local file).
If I print the response I get an HTTP 500 error... I am not sure what is causing the issue here because the server responds as it should when using the Curl command mentioned above. Is there some simple mistake I am making when looking at the code below?
HttpPost post = new HttpPost(postUrl);
HttpClient httpClient = HttpClientBuilder.create().build();
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(optionName, "cool"));
nvps.add(new BasicNameValuePair(file, "#myfile"));
try {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(post);
// do something with response
} catch (Exception e) {
e.printStackTrace();
}
Try to use a MultipartEntity instead of an UrlEncodedFormentity, to handle both parameters and file upload:
MultipartEntity entity = new MultipartEntity();
entity.addPart("optionName", "cool");
entity.addPart("file", new FileBody("/path/to/your/file"));
....
post.setEntity(entity);
Edit
MultipartEntity is deprecated and FileBody constructor takes a File, not a String, so:
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addTextBody("optionName", "cool");
entity.addPart("file", new FileBody(new File("/path/to/your/file")));
....
post.setEntity(entity.build());
Thanks #CODEBLACK .

How to send image with post request

I need to send post request with data in format like key=value and I am working that like ( url is url of ws and that is ok )
HttpEntityEnclosingRequestBase post=new HttpPost();
String result = "";
HttpClient httpclient = new DefaultHttpClient();
post.setURI(URI.create(url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (Entry<String, String> arg : args.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = getStringFromStream(instream);
instream.close();
}
return result;
This is ok when I send String data. My question is what to modify when one parameter is picture adn others are strings ?
When you are using multiple data types to send over a HttpClient you must use MultipartEntityBuilder(Class in org.apache.http.entity.mime)
try this out
MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
If you are looking to send the image as the data portion of the post request, you can follow some of the links posted in the comments.
If the image / binary data must absolutely be a header (which I wouldn't recommend), then you should use the encodeToString method inside of the Base64 Android class. I wouldn't recommend this for big images though since you need to load the entire image into memory as a byte array before you can even convert it to a string. Once you convert it to a string, its also 4/3 its previous size.
I think the answer you're looking for is in this post:
How to send an image through HTTPPost?
Emmanuel

Sending POST params with Netty and why isn't DefaultHttpDataFactory not in the releases?

HttpRequest httpReq=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,uri);
httpReq.setHeader(HttpHeaders.Names.HOST,host);
httpReq.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.KEEP_ALIVE);
httpReq.setHeader(HttpHeaders.Names.ACCEPT_ENCODING,HttpHeaders.Values.GZIP);
String params="a=b&c=d";
ChannelBuffer cb=ChannelBuffers.copiedBuffer(params,Charset.defaultCharset());
httpReq.setHeader(HttpHeaders.Names.CONTENT_LENGTH,cb.readableBytes());
httpReq.setContent(cb);
Does not yield a valid request. What is the correct way to send a post request, preferably by constructing the parameters data manually as opposed to with the DataFactory. Also, why is HttpDataFactory not included in any of the releases?
You wrote everything correct, just add httpReq.setHeader(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
and your example will work. For more complex code you need to add url encoding.
DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.toASCIIString());
request.headers().set(HttpHeaders.Names.HOST, ip);
request.headers().set(HttpHeaders.Names.CONTENT_TYPE,"application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
HttpEntity httpEntity = new UrlEncodedFormEntity(nvps);
ByteBuf byteBuf =
Unpooled.copiedBuffer(EntityUtils.toByteArray(httpEntity));
request.content().writeBytes(byteBuf);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH,request.content().readableBytes());
fu.channel().writeAndFlush(request)

Categories

Resources