0

I'm trying to post some compressed data plus text to a perl program on a web server but cannot change the header from octet-stream to multipart/form-data.

My code is:-

HttpClient httpclient = new DefaultHttpClient();
String url = "http://webaddress/perl.pl";
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type","multipart/form-data");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

try {

    entity.addPart("mtdata",new ByteArrayBody(data, file.getLastPathSegment()));
    entity.addPart("email", new StringBody(strUserName));
    entity.addPart("mtfilename", new StringBody(file.getLastPathSegment()));
    httppost.setEntity(entity);

    HttpResponse httpresponse = httpclient.execute(httppost);
    HttpEntity resEntity = httpresponse.getEntity();

    response = EntityUtils.toString(resEntity);
} 

The raw data being received is :-

Buffer = --FfT4ZNRUCPw6yONkpSsXNkA3WA2l6fvy53
Content-Disposition: form-data; name="mtdata"; filename="filename"
Content-Type: application/octet-stream             <<=== cannot change this

... Some binary data ...

What am I doing wrong?

Doug Conran
  • 437
  • 1
  • 5
  • 17

2 Answers2

1

In the end I found that the best way was to save it as a file and then post the file using MultipartEntity with a FileBody explicitly stating the Content-Type.

The code I used was:-

pairs.addPart("File", new FileBody(fout,"multipart/form-data"));

As an aside, I also found that I needed to use ZipOutputStream rather than GZIPOutputStream so that I could add the uncompressed file name.

Code for that was:-

data = bos.toByteArray();

OutputStream fos = new FileOutputStream(extStorageDirectory +  newfilename);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
try {
    ZipEntry entry = new ZipEntry(file.getLastPathSegment());
    zos.putNextEntry(entry);
    zos.write(data);
    zos.closeEntry();
}
finally {
    zos.close();
}
fos.close();
Doug Conran
  • 437
  • 1
  • 5
  • 17
0

Try insert

httppost.addHeader("Content-Type", "multipart/form-data");

and remove

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
StarsSky
  • 6,721
  • 6
  • 38
  • 63
  • I need the MultipartEntity because I'm sending both text and binary data. Also I tried using addHeader in place of setHeader but it made no difference. – Doug Conran Mar 17 '13 at 17:05