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();
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.
精彩评论