Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Curl -F" Java equivalent

Tags:

java

file

curl

What is the equivalent in java for the following curl command:

curl -X POST -F "file=@$File_PATH"

The request I want to execute using Java is :

curl -X POST -F 'file=@file_path' http://localhost/files/ 

I was trying :

            HttpClient httpClient = new DefaultHttpClient();        

    HttpPost httpPost = new HttpPost(_URL);

    File file = new File(PATH);

            MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file, "bin");
        mpEntity.addPart("userfile", cbFile);

        httpPost.setEntity(mpEntity);

    HttpResponse response = httpClient.execute(httpPost);
    InputStream instream = response.getEntity().getContent();
like image 976
amine Avatar asked Oct 10 '11 13:10

amine


1 Answers

I ran across this problem yesterday. Here is a solution that uses Apache http libraries.

package curldashf;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.util.EntityUtils;

public class CurlDashF
{
    public static void main(String[] args) throws ClientProtocolException, IOException
    {
        String filePath = "file_path";
        String url = "http://localhost/files";
        File file = new File(filePath);
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(file));
        HttpResponse returnResponse = Request.Post(url)
            .body(entity)
            .execute().returnResponse();
        System.out.println("Response status: " + returnResponse.getStatusLine().getStatusCode());
        System.out.println(EntityUtils.toString(returnResponse.getEntity()));
    }
}

Set filePath and url as necessary. If you are using something other than a file, you can substitute FileBody with ByteArrayBody, InputStreamBody or StringBody. My particular situation called for ByteArrayBody but the code above works for a file.

like image 163
tjmorrison Avatar answered Nov 08 '22 07:11

tjmorrison