I am using Apache HttpComponents' HttpClient to upload files to a third party web interface. Code looks like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("UPLOAD_URL");
FileBody bin = new FileBody(file, filename, "text/csv", "UTF-8");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Username", new StringBody("User"));
reqEntity.addPart("Password", new StringBody("Password"));
reqEntity.addPart("bin", bin);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
This is working as expected.
As this data is sensitive, I don't want it to be stored on the client side. (The program retrieves this data from a web service. I only created the file for the purpose of uploading it.)
So I'm looking for a way to not use a real file, but replace it was some kind of in-memory representation. I tried to use InputStreamBody instead, but those requests get denied by the third party system.
Any ideas how this can be done?
Looks like the problem with using InputStreamBody is the getContentLength method, which looks like this:
public long getContentLength() {
return -1;
}
This results in a chunked HTTP POST (Transfer-Encoding: chunked), which seems to be not understood by that particular web interface. So, I ended up extending InputStreamBody like this:
public class NoFileBody extends InputStreamBody {
private final long length;
public NoFileBody(final InputStream in, final String mimeType, final String filename, final long length) {
super(in, mimeType, filename);
this.length = length;
}
@Override
public long getContentLength() {
return length;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With