【问题标题】:"Curl -F" Java equivalent"Curl -F" Java 等效项
【发布时间】:2011-10-10 13:08:53
【问题描述】:

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

【问题讨论】:

  • 您的问题到底是什么?还有一点 mroe 代码会很有帮助,例如 httpPost 是什么?
  • 我正在尝试使用 java 程序发送 curl 命令(已经是 Linux 终端命令)。我已经尝试过多部分,但我不需要上传或下载文件,它只是在远程存储库之间传输。
  • 好吧,您的 Java 代码不完整。而且我们不知道为什么它不起作用。所以请发布更多代码(是的,我们都知道curl 是什么......叹息)。例如。您没有调用任何 post 方法,因此上面的片段显然无法工作。你至少需要一个 HttpURLConnection ...
  • 我正在使用 org.apache.http.client 与 REST 服务器进行通信。我已经使用 cURL 提出了请求。我现在要做的是从 java 程序执行这些请求。问题是其中一个请求需要进行文件传输,用 curl 是使用 -F 选项进行的,问题是如何在 java 中进行?

标签: java file curl


【解决方案1】:

我昨天遇到了这个问题。这是一个使用 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。如果您使用的不是文件,则可以将 FileBody 替换为 ByteArrayBody、InputStreamBody 或 StringBody。我的特殊情况需要 ByteArrayBody 但上面的代码适用于文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 2010-09-12
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2011-10-12
    相关资源
    最近更新 更多