【问题标题】:Add parameters to Apache HttpPost向 Apache HttpPost 添加参数
【发布时间】:2010-07-29 23:58:33
【问题描述】:

我正在尝试将文件发送到 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");

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

我让它工作的唯一方法是将这些参数设置为标题(setHeader 和 getHeader),但这不是一个选项。

有什么建议吗?或者您能否将我重定向到文件+参数上传的完整示例?
谢谢,
亚历克斯

【问题讨论】:

    标签: java post parameters httpclient


    【解决方案1】:

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

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

    无法编译。

    【讨论】:

    • @YoK 你能告诉我可以通过 setEntity() 发送的参数的最大大小吗? httppost.setEntity(parameter) 有什么限制吗?
    【解决方案2】:

    如果您使用 servlet 3.0,您可以尝试将 @MultipartConfig 添加到您的 servlet。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2012-01-04
      相关资源
      最近更新 更多