我想发布(在 Java 中)一个多部分/混合请求,其中一部分是“应用程序/json”类型,另一部分是“应用程序/pdf”类型。有谁知道图书馆可以让我轻松做到这一点?令人惊讶的是,我一直找不到。
我将生成 JSON,但我需要能够将该部分的内容类型设置为“application/json”。
非常感谢,丹尼尔
很简单,使用Apache Http-client 库(此代码使用 4.1 版和 jars httpclient、httpcore 和 httpmime),这是一个示例:
package com.officedrop.uploader;
import java.io.File;
import java.net.URL;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class SampleUploader {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
String basePath = "http://localhost/";
URL url = new URL( basePath );
HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
HttpPost httpost = new HttpPost( String.format( "%s%s", basePath, "ze/api/documents.xml"));
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file_1", new FileBody( new File( "path-to-file.pdf" ) , "file.pdf", "application/pdf", null));
entity.addPart("uploaded_data_1", new FileBody( new File( "path-to-file.json" ) , "file.json", "application/json", null));
httpost.setEntity(entity);
HttpResponse response = httpclient.execute( targetHost, httpost);
}
}