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.
Advertisement
Answer
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);