0

我正在尝试将一些压缩数据和文本发布到 Web 服务器上的 perl 程序,但无法将标头从八位字节流更改为多部分/表单数据。

我的代码是:-

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 ...

我究竟做错了什么?

4

2 回答 2

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();
于 2013-03-18T21:17:41.473 回答
0

尝试插入

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

并删除

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
于 2013-03-17T16:09:57.283 回答