【问题标题】:Send Byte array as file in using http client in java在java中使用http客户端发送字节数组作为文件
【发布时间】:2013-03-14 10:05:30
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: java bytearray httpclient


    【解决方案1】:

    您可以使用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);
    

    【讨论】:

      【解决方案2】:

      你可以这样做

      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);
      

      【讨论】:

      • 使用的是哪个版本?我用过 4.0.1
      • 任何方式,他都可以根据所用版本的语法使用InputStreamBody
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多