使用InputStream上载文件时出现Java Apache HttpClient错误

时间:2015-09-15 21:50:49

标签: http cxf apache-httpclient-4.x

我对输入流有同样的问题。您能否请分享有关您的修复程序的更多详细信息。

谢谢, 戒日

链接到您的问题

Java Apache HttpClient error uploading files

4 个答案:

答案 0 :(得分:1)

如果你知道你的contentLength-

,我们可以覆盖InputStreamBody.getContentLength而不需要创建我们自己的ContentBody实现的另一种简单方法
InputStreamBody inputStreamBody = new InputStreamBody(inputStream, ContentType.APPLICATION_OCTET_STREAM, fileName){
                @Override
                public long getContentLength(){return contentLength;}
            };

MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addPart("dataAsStream", inputStreamBody)
            .build();

答案 1 :(得分:0)

扩展org.apache.http.entity.mime.content.InputStreamBody的代码将是这样的。在创建InputStreamBodyExtended

之前,您需要以某种方式计算正确的内容长度
public class InputStreamBodyExtended extends InputStreamBody {

  private long contentLength = -1; 

  public InputStreamBodyExtended(InputStream in, String filename, long contentLength) {
    super(in, filename);
    this.contentLength = contentLength;
  }

  public InputStreamBodyExtended(InputStream in, ContentType contentType, long contentLength) {
    super(in, contentType);
    this.contentLength = contentLength;
  }

  public InputStreamBodyExtended(InputStream in, ContentType contentType,
        String filename, long contentLength) {
    super(in, contentType, filename);
    this.contentLength = contentLength;
  }

  @Override
  public long getContentLength() {
    return contentLength;
  }

}

答案 2 :(得分:0)

另一个选项是org.apache.http.entity.mime.content.ByteArrayBody,如果事先不知道大小是什么(!!!你必须确保inputStream的内容适合JVM的内存):

InputStream inputStream = // get your input stream somehow
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int i;
    byte buff[] = new byte[4096];
    while( -1 != (i = inputStream.read(buff))){
        baos.write(buff, 0, i);
    }
    ByteArrayBody bab = new ByteArrayBody(baos.toByteArray(), "fileName1");

答案 3 :(得分:0)

以下是我如何解决它。

<table>
  <tr>
    <td>Row one, cell one</td>
    <td>Row one, cell two</td>
  </tr>
  <tr>
    <td>Row two, cell one</td>
    <td>Row two, cell two</td>
  </tr>
  <tr>
    <td>Row three, cell one</td>
    <td>Row four, cell two</td>
  </tr>
</table>