[英]Add parameters to 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中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.