Am having the same issue with inputstream. Can you please share more details about your fix please.
Thanks, Harsha
link to your question
Am having the same issue with inputstream. Can you please share more details about your fix please.
Thanks, Harsha
link to your question
There is another simple way we can override InputStreamBody.getContentLength
without a need to create our own ContentBody
implementation if you know your contentLength-
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();
The code of the extended org.apache.http.entity.mime.content.InputStreamBody
will be something like this. You will need to somehow calculate the correct content length before creating the 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;
}
}
An other option is org.apache.http.entity.mime.content.ByteArrayBody
, if don't know what is the size beforehand (!!! You have to be sure that the content of the inputStream will fit into the memory of 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");
Here is how I solved it.
public class CustomInputStreamBody extends InputStreamBody {
private InputStream inputStream;
private BufferedReader bufferedReader = null;
StringBuilder stringBuilder = null;
public CustomInputStreamBody(InputStream in,ContentType contentType){
super(in,contentType);
this.inputStream=in;
}
@Override
public long getContentLength() {
int length=0;
byte[] bytes=null;
try {
bytes = IOUtils.readBytesFromStream(inputStream);
// iterate to get the data and append in StringBuilder
System.out.println("___________"+bytes.length);
}catch (IOException ioe){
ioe.printStackTrace();
}
return bytes.length;
}