“Curl -F”Java等价物

时间:2011-10-10 13:08:54

标签: java file curl

以下curl命令在java中的等价物是什么:

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

我想用Java执行的请求是:

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

我在尝试:

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

1 个答案:

答案 0 :(得分:2)

昨天我遇到了这个问题。这是一个使用Apache http库的解决方案。

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

根据需要设置filePath和url。如果您使用的是文件以外的其他内容,则可以使用ByteArrayBody,InputStreamBody或StringBody替换FileBody。我的特殊情况需要ByteArrayBody,但上面的代码适用于文件。