Making a Multi-Part Form Data Post Request with Java
The advent of Apache Commons HttpClient version 4.0 eliminated the ability to perform multipart/form-data POST requests that were possible in version 3.x. The HttpClient team explained that multipart functionality fell outside the scope of their core activities and recommended seeking alternative libraries.
Finding a Suitable Java Library
The question arises as to which Java libraries offer multipart/form-data POST request capabilities. One such library is HttpClient 4.x, which provides a comprehensive solution for making these requests.
Updated HttpClient 4.3 Code
With HttpClient versions 4.3 and above, the API has been updated and some classes have been deprecated. The following code snippet illustrates the revised method for making multipart file posts:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost("..."); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); // This attaches the file to the POST: File f = new File("[/path/to/upload]"); builder.addBinaryBody( "file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName() ); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity();
Deprecated HttpClient 4.0 Code (for reference)
HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); FileBody bin = new FileBody(new File(fileName)); StringBody comment = new StringBody("Filename: " fileName); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("bin", bin); reqEntity.addPart("comment", comment); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity();
With these libraries, developers can seamlessly create HTTP clients capable of making multipart/form-data POST requests, enabling them to interact with Web services and APIs that require this type of request format.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3