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

前端之家收集整理的这篇文章主要介绍了在Java中生成混合/多部分HTTP请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

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

非常感谢,
丹尼尔

最佳答案
简单,使用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);

    }

}
原文链接:https://www.f2er.com/java/438099.html

猜你在找的Java相关文章