Add parameters to Apache HttpPost

a 夏天 提交于 2019-12-21 21:08:49

问题


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());

...

on the server side, we've got:

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.

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?

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

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


回答1:


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();

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

reqEntity.addPart("bin", bin);

would not compile.




回答2:


if you use servlet 3.0, you can try add @MultipartConfig onto your servlet.



来源:https://stackoverflow.com/questions/3367870/add-parameters-to-apache-httppost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!