I ran into this problem yesterday. Here is a solution using 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()));
}
}
Install the path and url file if necessary. If you use something other than a file, you can replace FileBody with ByteArrayBody, InputStreamBody or StringBody. In my specific situation, ByteArrayBody is called, but the code above works for the file.
source
share