5

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'. 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'.

Many thanks, Daniel

1 Answer 1

4

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

    }

}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Maurício, thanks for the suggestion. However the request is generated with a 'multipart/form-data' content-type instead of 'multipart/mixed'. I haven't found a way to change that, do you know how?
Why do you need it to be mixed? Any specific reason? Any HTTP server/framework will be able to decode these files correctly.
The documentation for the service I'm calling requires mixed, but it appears now that the documentation is in error. :) Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.