Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate mixed/multipart HTTP request in Java

Tags:

java

http

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

like image 743
Daniel Avatar asked Oct 07 '22 16:10

Daniel


1 Answers

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

    }

}
like image 149
Maurício Linhares Avatar answered Oct 10 '22 07:10

Maurício Linhares