将参数添加到Apache HttpPost [英] Add parameters to Apache HttpPost

查看:119
本文介绍了将参数添加到Apache HttpPost的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件发送到Servlet。
除了这个文件,我还必须发送一些参数(即名称/ ID,日期和其他一些参数)。我在客户端使用HttpClient,在服务器端使用ServerFileUpload。

I'm trying to send a file to a Servlet. Along with this file, I also have to send some parameters (i.e. name/id, date and a few others). I'm using HttpClient on client-side and ServerFileUpload on server-side.

这是客户端代码:
...

This is the client-side code: ...

String url = "http://localhost:8080/RicezioneServlet/RicezioneServlet";
HttpClient httpclient = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(url);
MultipartEntity mpe = new MultipartEntity();
//I'm sending a .zip file
ContentBody cb = new FileBody(fileToSend,"application/zip");
mpe.addPart("file", cb);
postMethod.setEntity(mpe);
HttpResponse resp = httpclient.execute(postMethod);
HttpEntity respEntity = resp.getEntity();
System.out.println(resp.getStatusLine());

...

方面,我们有:

ServletFileUpload sup = new ServletFileUpload();
FileItemIterator it = sup.getItemIterator(request);
FileItemStream item = it.next();
InputStream ios = item.openStream();
//read from ios and write to a fileoutputstream.

现在,我不知道如何将上述参数添加到请求中...我试过使用StringBody并将其添加到MultiPartEntity,但我得到一个NullPointerException:

Now, I don't know how to add the aforementioned parameters to the request... I tried to use a StringBody and to add it to the MultiPartEntity, but I get a NullPointerException at:

String author = request.getParameter("author");

这意味着该参数不被视为参数,也许?

which means that the parameter isn't seen as a parameter, maybe?

我唯一能做的就是将这些参数设置为Headers(setHeader和getHeader),但这不是一个选项。

The only was I got it working was setting these parameters as Headers (setHeader and getHeader), but this is not an option.

有什么建议吗?或者你可以将我重定向到文件+参数上传的完整示例吗?

谢谢,

Alex

Any advice? Or maybe can you redirect me to a full example of file+parameter upload?
Thanks,
Alex

推荐答案

尝试使用粘贴在此处的类似代码:

Try using similar code as pasted here :

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

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

您还需要添加外部jar apache-mime4j-0.6.jar(org.apache。 james.mime4j)否则

You will also need to add the external jar apache-mime4j-0.6.jar (org.apache.james.mime4j) otherwise

reqEntity.addPart("bin", bin);

无法编译。

这篇关于将参数添加到Apache HttpPost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆