Как я могу сделать запрос multipart/form-data POST с помощью Java?
в дни версии 3.x из Apache Commons HttpClient, что делает запрос multipart / form-data POST возможным (пример из 2004). К сожалению, это больше не возможно в версия 4.0 HttpClient.
для нашей основной деятельности "HTTP", multipart несколько
из области видимости. Мы хотели бы использовать составной код, поддерживаемый некоторыми
другой проект, для которого он находится в области, но я не знаю ни одного.
Мы пытались сдвинуть составной код для общего пользования-кодек несколько лет
назад, но я туда не летал. Олег недавно упомянул еще одну
проект, который имеет составной код синтаксического анализа и может быть заинтересован
в нашем составном коде форматирования. Я не знаю текущий статус
на этом. (http://www.nabble.com/multipart-form-data-in-4.0-td14224819.html)
кто-нибудь знает о какой-либо библиотеке Java, которая позволяет мне написать HTTP-клиент, который может сделать сообщение multipart / form-data просьба?
фон: я хочу использовать удаленный API Zoho Writer.
8 ответов:
мы используем HttpClient 4.x чтобы сделать составной файл post.
обновление по состоянию на HttpClient 4.3 некоторые классы были осуждены. Вот код, с новым API:
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();Ниже приведен исходный фрагмент кода с устаревший HttpClient 4.0 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();
Это зависимости Maven у меня есть.
Java-Кода:
HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); FileBody uploadFilePart = new FileBody(uploadFile); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("upload-file", uploadFilePart); httpPost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpPost);зависимости Maven в pom.XML-код:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.0.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.0.1</version> <scope>compile</scope> </dependency>
Если размер JARs имеет значение (например, в случае апплета), можно также напрямую использовать httpmime с java.net.HttpURLConnection вместо HttpClient.
httpclient-4.2.4: 423KB httpmime-4.2.4: 26KB httpcore-4.2.4: 222KB commons-codec-1.6: 228KB commons-logging-1.1.1: 60KB Sum: 959KB httpmime-4.2.4: 26KB httpcore-4.2.4: 222KB Sum: 248KBкод:
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(new File(fileName)); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); ...зависимость в pom.XML-код:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.2.4</version> </dependency>
используйте этот код для загрузки изображений или любых других файлов на сервер с помощью post in multipart.
import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; public class SimplePostRequestTest { public static void main(String[] args) throws UnsupportedEncodingException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo"); try { FileBody bin = new FileBody(new File("/home/ubuntu/cd.png")); StringBody id = new StringBody("3"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("upload_image", bin); reqEntity.addPart("id", id); reqEntity.addPart("image_title", new StringBody("CoolPic")); httppost.setEntity(reqEntity); System.out.println("Requesting : " + httppost.getRequestLine()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); System.out.println("responseBody : " + responseBody); } catch (ClientProtocolException e) { } finally { httpclient.getConnectionManager().shutdown(); } } }это требует ниже файлов для загрузки.
библиотеки
httpclient-4.1.2.jar,httpcore-4.1.2.jar,httpmime-4.1.2.jar,httpclient-cache-4.1.2.jar,commons-codec.jarиcommons-logging-1.1.1.jarчтобы быть в classpath.
вы также можете использовать уверены который строится на HTTP-клиенте. Все очень просто:
given().multiPart(new File("/somedir/file.bin")).when().post("/fileUpload");
httpcomponents-client-4.0.1работал для меня. Однако мне пришлось добавить внешнюю банкуapache-mime4j-0.6.jar(орг.апаш.Джеймс.mime4j) в противном случаеreqEntity.addPart("bin", bin);не будет компилироваться. Теперь это работает как шарм.
нашел этот пример в Apache Краткое Руководство. Это для версии 4.5:
/** * Example how to use multipart/form encoded POST request. */ public class ClientMultipartFormPost { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("bin", bin) .addPart("comment", comment) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } } }
У нас есть чистая реализация java multipart-form submit без использования каких-либо внешних зависимостей или библиотек за пределами jdk. См https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java
private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}"; private static String subdata1 = "@@ -2,3 +2,4 @@\r\n"; private static String subdata2 = "<data>subdata2</data>"; public static void main(String[] args) throws Exception{ String url = "https://" + ip + ":" + port + "/dataupload"; String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes()); MultipartBuilder multipart = new MultipartBuilder(url,token); multipart.addFormField("entity", "main", "application/json",body); multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1); multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2); List<String> response = multipart.finish(); for (String line : response) { System.out.println(line); } }
Comments