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?

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

0

Try insert

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

and remove

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.