在Java中生成混合/多部分HTTP请求

时间:2012-05-30 19:17:11

标签: java http

我想POST(在Java中)一个multipart / mixed请求,其中一个部分是'application / json'类型,另一个是'application / pdf'类型。有谁知道一个图书馆,这将允许我轻松地这样做?令人惊讶的是我找不到一个。

我将生成JSON,但我需要能够将该部分的内容类型设置为'application / json'。

非常感谢, 丹尼尔

1 个答案:

答案 0 :(得分:4)

很简单,使用Apache Http-client library(此代码使用版本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);

    }

}