HTTP's multipart/form-data encoding is commonly used for file uploads, allowing clients to send both text and binary data in a single request. While Apache Commons HttpClient 3.x supported this functionality, it was removed in version 4.0. This article explores alternative Java libraries that enable multipart/form-data POST requests.
Despite reaching out to the HttpClient project, there are no known efforts to re-implement multipart support. As such, developers must seek alternative solutions for their multipart/form-data needs.
Solution
HttpClient 4.x, the current stable version, offers a more modern API for handling multipart requests. Here's an example using the updated API:
CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost("..."); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); 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();
For developers still using HttpClient 4.0 (not recommended), the following code snippet uses the deprecated API:
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();
Other Java libraries that support multipart/form-data POST requests include:
The above is the detailed content of How to Make Multipart/Form-Data POST Requests in Java?. For more information, please follow other related articles on the PHP Chinese website!