“Curl -F”Java等效项

83qze16e  于 2023-05-21  发布在  Java
关注(0)|答案(1)|浏览(93)

下面的命令在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();
wgmfuz8q

wgmfuz8q1#

我昨天偶然遇到了这个问题。下面是一个使用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,但上面的代码适用于文件。

相关问题