我正在尝试将一些压缩数据和文本发布到Web服务器上的perl程序,但无法将标头从octet-stream更改为multipart / form-data。
我的代码是: -
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);
}
收到的原始数据是: -
Buffer = --FfT4ZNRUCPw6yONkpSsXNkA3WA2l6fvy53
Content-Disposition: form-data; name="mtdata"; filename="filename"
Content-Type: application/octet-stream <<=== cannot change this
... Some binary data ...
我做错了什么?
答案 0 :(得分:1)
最后,我发现最好的方法是将其保存为文件,然后使用MultipartEntity发布文件,并使用FileBody明确说明Content-Type。
我使用的代码是: -
pairs.addPart("File", new FileBody(fout,"multipart/form-data"));
另外,我还发现我需要使用ZipOutputStream而不是GZIPOutputStream,以便我可以添加未压缩的文件名。
代码是: -
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();
答案 1 :(得分:0)
尝试插入
httppost.addHeader("Content-Type", "multipart/form-data");
并删除
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);