Making a Multipart/Form-Data POST Request in Java

<dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.4</version> </dependency> </dependencies> 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(); 4.0 版本需要按照下面...

August 27, 2024 · 1 min · 231 words · Lucius Chen