java中的等效cURL --data-binary @filename -H“Content-Type:text / csv”

时间:2018-03-06 03:51:45

标签: java http curl

我正在使用Apache http客户端,使用cURL,命令将是:

curl -i -X POST --data-binary @data.csv -H "Content-Type:text/csv" "http://localhost:8080/"

Java(Apache Http Client)中的等价物是什么?我尝试了以下方法:

HttpPost postRequest = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("data.csv");
builder.addBinaryBody("upfile", file, ContentType.create("text/csv"), "data.csv");
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
client.execute(postRequest);

1 个答案:

答案 0 :(得分:1)

curl直接将文件内容作为正文(实体)发送,而不是在多部分中发送。尝试

    HttpPost post = new HttpPost(url);
    post.setEntity(new FileEntity(new File(filename),ContentType.create("text/csv")));
    ... client.execute(post) ...

PS:curl -d/--data[-*]已使用POST,您不需要-X