我想在Java中发出一个multipart/mixed请求,其中一部分是类型为'application/json',另一部分是类型为'application/pdf'。 有没有人知道一个库可以让我轻松地完成这个过程?令人惊讶的是,我还没有找到一个。
我将生成JSON,但我需要能够设置该部分的内容类型为'application/json'。
谢谢, 丹尼尔
我将生成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);
}
}