java 在java中使用http客户端将字节数组作为文件发送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15406213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:28:52  来源:igfitidea点击:

Send Byte array as file in using http client in java

javabytearrayhttpclient

提问by Hossein Nasr

We have byte array of file and we want to upload it as file. FileBodyonly gets Fileas parameter but we have a array of bytes.

我们有文件的字节数组,我们想将它作为文件上传。 FileBodyFile作为参数获取,但我们有一个字节数组。

One solution is to save byte array into file and then send it but it is not appropriate for me.

一种解决方案是将字节数组保存到文件中然后发送,但它不适合我。

byte b[]= new byte[1000];
//fill b
MultipartEntity form = new MultipartEntity();
form.addPart("file", new FileBody(/* b? */));

thanks.

谢谢。

回答by Arun P Johny

You can do something like

你可以做类似的事情

HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new InputStreamBody(new ByteArrayInputStream(b), "my-file.txt");
form.addPart("file", cd);

HttpEntityEnclosingRequestBase post = new HttpPost("");//If a PUT request then `new HttpPut("");`
post.setEntity(form);
client.execute(post);

回答by Frédéric Chopin

You can use ByteArrayBodyinstead InputStreamBody or FileBody.

您可以使用ByteArrayBody代替 InputStreamBody 或 FileBody。

HttpClient client=null;
byte b[]= new byte[1000];
MultipartEntity form = new MultipartEntity();
ContentBody cd = new ByteArrayBody(b, "my-file.txt");
form.addPart("file", cd);

HttpEntityEnclosingRequestBase post = new HttpPost("");
post.setEntity(form);
client.execute(post);