加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

“Curl -F”Java等价物

发布时间:2020-12-14 02:12:23 所属栏目:Linux 来源:网络整理
导读:以下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
以下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();

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读