简体   繁体   English

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

[英]Generate mixed/multipart HTTP request in Java

I would like to POST (in Java) a multipart/mixed request, where one part is of type 'application/json' and the other of type 'application/pdf'. 我想POST(在Java中)一个multipart / mixed请求,其中一个部分是'application / json'类型,另一个是'application / pdf'类型。 Does anyone know of a library which will allow me to do this easily? 有谁知道一个图书馆,这将允许我轻松地这样做? Surprisingly I haven't been able to find one. 令人惊讶的是我找不到一个。

I'll generate the JSON, but I need to be able to set the content type of that part to 'application/json'. 我将生成JSON,但我需要能够将该部分的内容类型设置为'application / json'。

Many thanks, Daniel 非常感谢,丹尼尔

Easy, use the Apache Http-client library (this code used version 4.1 and the jars httpclient, httpcore and httpmime), here's a sample: 很简单,使用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);

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM