Creating a mixed / multi-line HTTP request in Java

I would like POST (in Java) to be a multi-page / mixed request, with one part being of type "application / json" and the other of type "application / pdf". Does anyone know a library that will allow me to do this easily? Surprisingly, I could not find him.

I will create JSON, but I need to set the content type of this part to "application / json".

Thanks a lot Daniel

+5
source share
1 answer

Just use the Apache Http client library (this code used version 4.1 and jars httpclient, httpcore and httpmime), here is a sample

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);

    }

}
+4
source

All Articles