HttpPost不能设置header为multipart/form-data



我正试图将一些压缩数据加上文本发布到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 ...

我做错了什么?

最后,我发现最好的方法是将其保存为文件,然后使用multiparentity和一个明确声明Content-Type的FileBody发布该文件。

我使用的代码是:-
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();

尝试插入

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

和删除

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

相关内容

  • 没有找到相关文章

最新更新