将参数添加到Apache HttpPost
我正在尝试将文件发送到Servlet。 除了这个文件,我还必须发送一些参数(即名称/ ID,日期和其他几个)。 我在客户端使用HttpClient,在服务器端使用ServerFileUpload。
这是客户端代码:…
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:
String author = request.getParameter("author");
这意味着该参数不被视为参数,也许?
我得到它的唯一工作是将这些参数设置为Headers(setHeader和getHeader),但这不是一个选项。
任何建议? 或者你可以将我重定向到文件+参数上传的完整示例吗?
谢谢,
亚历克斯
尝试使用粘贴在此处的类似代码:
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)否则
reqEntity.addPart("bin", bin);
不会编译。
如果使用servlet 3.0,可以尝试将@MultipartConfig添加到servlet中。
- httpclientexception“org.apache.http.conn.ConnectionPoolTimeoutException:超时等待连接”
- 如何确保我的HttpClient 4.1不会泄漏套接字?
- java.lang.NoSuchFieldError:INSTANCE
- 如何在Netty客户端中使用Socks4 / 5代理处理程序(4.1)
- 如何使用简单的String(字符串格式的xml)调用SOAP Web服务
- 来自commons-httpclient-3.1的URIUtil.encodePath发生了什么?
- 使用HttpClient上传video文件
- HttpClient 4.2,基本身份validation和AuthScope
- 如何使用Java登录网站