java的fclient_“Curl -F”Java等价物

以下curl命令在

java中的等价物是什么:

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

我想用Java执行的请求是:

curl -X POST -F [email protected]_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,但上面的代码适用于文件.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值