如果 JAWS 应用程序失败,我正在编写一些代码以通过 http 将日志文件发送到服务器。为了测试这一点,我设置了一个接收和处理请求的 servlet。
我的客户端代码来自 Apache HttpClient 4.2示例
{
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/testServer/testserv/a");
FileBody bin = new FileBody(new File("XXXs"));
StringBody comment = new StringBody("A binary file of some kind");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
}
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:8080/testServer/testserv/a");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
httpPost.releaseConnection();
}
}
我的服务器端使用Apache FileUpload的教程
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
try {
List<FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
File uploadedFile = new File("XXX");
try {
item.write(uploadedFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(uploadedFile.getAbsolutePath());
}
} catch (FileUploadException e) {
System.out.println("File Upload Exception");
e.printStackTrace();
}
} else{
System.out.println("Not multi part");
System.out.println(request.getParameterMap());
}
我正在使用 JBoss AS7。结果是,如果我不添加FileEntity
到MultiPartEntity
请求被处理。否则会引发 FileUpload 异常。
Processing of multipart/form-data request failed. Stream ended unexpectedly
我在使用 JBoss 和这里的其他工具方面不是很有经验,因此非常感谢您的帮助和耐心。