HttpClient应用 与 Servlet 处理文件上传

来源:互联网 发布:ubuntu kvm安装win7 编辑:程序博客网 时间:2024/06/07 22:08
 
HttpClient应用 与 Servlet 处理文件上传

1、HttpClient模拟客户端提交,上传文件,提交表单

2、使用servlet处理上传的文件


现在HttpClient 版本到4 了,我现在用的是commons-httpclient-3.0.1,4和3两个版本的用法有较大的差别,另外,HttpClient依赖一些commos包,象 ‍commons-logging,‍commons-beanutils等,使用的时候记得要加入,我会把我实验通过的版本上传到csdn上,在本文的最低端加上资源连接,读者用到的时候就不用再去各个地方找资源了。

使用servelet处理上传资源的时候用到第三方的包:commons-fileupload-1.2.2.jar,它又依赖包:commons-io-1.3.2.jar,‍catalina-manager.jar,记得引入。


HttpClient 模拟客户端:


‍package com.http.test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;

public class HttpClientUtile {

public String sendMail(String url) {
   String strResponse = "";
   // 构造HttpClient的实例
   HttpClient httpClient = new HttpClient();
   // 创建POST方法的实例
   PostMethod postMethod = new PostMethod(url);
   // 填入各个表单域的值
   NameValuePair[] data = { new NameValuePair("sign", "agsend"),
     new NameValuePair("From", "EMAIL"),
     new NameValuePair("to", "to"),
     new NameValuePair("subject", "subject"),
     new NameValuePair("body", "body"),
     new NameValuePair("password", "PASSWORD") };
   // 将表单的值放入postMethod中
   postMethod.setRequestBody(data);
   try {
    httpClient.getParams().setContentCharset("GBK");
    // 执行postMethod
    int statusCode = httpClient.executeMethod(postMethod);
    // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
    // 301或者302
//    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
//      || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
//     String responseBody = postMethod.getResponseBodyAsString();
//     log.info(responseBody);
//     if (responseBody != null) {
//      if ("succ".equals(responseBody)) { // 发送成功
//
//       isSended = true;
//      }
//     }
//    }
  
    if (statusCode == 200) {
     strResponse = postMethod.getResponseBodyAsString();
    }
   } catch (IllegalArgumentException e) {
    e.printStackTrace();
   } catch (HttpException e) {
    // 发生致命的异常,可能是协议不对或者返回的内容有问题

    e.printStackTrace();
   } catch (IOException e) {
    // 发生网络异常
    e.printStackTrace();
   } finally {
    // 释放连接
    postMethod.releaseConnection();
   }
   return strResponse;

}
/**
* @category 此方法经过验证行不通,就是上传文件和普通的域提交不能同时进行,请各位再加实验
* @param strUrl
* @param strFrom
* @param strTo
* @param strTitle
* @param strBody
* @param strFiles
* @return
*/
public String sendMail(String strUrl,String strFrom,String strTo ,String strTitle,String strBody,String strFiles)
{
   String strResponse = null;
   HttpClient httpClient = new HttpClient();
   MultipartPostMethod multipartPostMethod = new MultipartPostMethod(strUrl);
   try {
    multipartPostMethod.addParameter("from",strFrom);
    multipartPostMethod.addParameter("to",strTo);
    multipartPostMethod.addParameter("title",strTitle);
    multipartPostMethod.addParameter("body",strBody);
    String strFileName = "aaa";
    if (strFiles.indexOf("/")>0) {
   
     String[] strTmp = strFiles.split("/");
     strFileName = strTmp[strTmp.length-1];
    }
    if (strFiles.indexOf("\\\\")>0) {
   
     String[] strTmp = strFiles.split("\\\\");
     strFileName = strTmp[strTmp.length-1];
    }
    multipartPostMethod.addParameter("file",strFileName,new File(strFiles));
    multipartPostMethod.addPart(new FilePart(strFileName,new File(strFiles)));
    //httpClient.getParams().setContentCharset("UTF-8");
  
    PostMethod postMethod = new PostMethod(strUrl);
    NameValuePair[] data = {
      new NameValuePair("from", "EMAIL"),
      new NameValuePair("to", "to"),
      new NameValuePair("title", "subject"),
      new NameValuePair("body", "body") };
    postMethod.setRequestBody(data);
    //int statusCode = httpClient.executeMethod(postMethod);
    int statusCode = httpClient.executeMethod(multipartPostMethod);
    if (statusCode == 200) {
     strResponse = multipartPostMethod.getResponseBodyAsString();
    }
   } catch (Exception e){
    e.printStackTrace();
   }
   finally
   {
    multipartPostMethod.releaseConnection();
   }
   return strResponse;
}
public String uploadFiles(String strUrl, String[] strFiles)
{
   String strResponse = null;
   HttpClient httpClient = new HttpClient();
   MultipartPostMethod multipartPostMethod = new MultipartPostMethod(strUrl);
   try {
  
    for (int i = 0; i < strFiles.length; i++) {
     multipartPostMethod.addPart(new FilePart("file"+i,new File(strFiles[i])));
    }
    int statusCode = httpClient.executeMethod(multipartPostMethod);
    if (statusCode == 200) {
     strResponse = multipartPostMethod.getResponseBodyAsString();
    }
   } catch (Exception e){
    e.printStackTrace();
   }
   finally
   {
    multipartPostMethod.releaseConnection();
   }
   return strResponse;
}
public String uploadFiles(String strUrl,String strFrom, String strFiles)
{
   String strResponse = null;
   HttpClient httpClient = new HttpClient();
   PostMethod postMethod = new PostMethod(strUrl);
   try {
    FilePart filePart = new FilePart("file","aa.txt",new File(strFiles));
    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(new Part[]{new StringPart("HIDDEN","from",strFrom),filePart},postMethod.getParams());

    postMethod.addParameter(new NameValuePair("from",strFrom));
  
    postMethod.setRequestEntity(multipartRequestEntity);
  
    httpClient.getParams().setContentCharset("UTF-8");
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode == 200) {
     strResponse = postMethod.getResponseBodyAsString();
    }
   } catch (Exception e){
    e.printStackTrace();
   }
   finally
   {
    postMethod.releaseConnection();
   }
   return strResponse;
}
/**
* @category 上传附件
* @param strUrl
* @param strFiles
* @return 返回状态码 200 正常
* @throws Exception
*/
public String uploadFiles(String strUrl,String attachments) throws Exception
{
   String strResponse = null;
   HttpClient httpClient = new HttpClient();
   MultipartPostMethod postMethod = new MultipartPostMethod(strUrl.trim());
   try {
    if (null != attachments && attachments.trim().length()>0) {
     String [] strArr = attachments.trim().split("\\|");
     for (int i = 0; i < strArr.length; i++) {
      if (null!= strArr[i] && strArr[i].trim().length()>0) {
       String fileName = strArr[i].trim();
       fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
       fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
       String[] strTmpNameArr = fileName.split("/");
       if (strTmpNameArr.length>0) {
        fileName = strTmpNameArr[strTmpNameArr.length-1];
        postMethod.addPart(new FilePart(fileName,new File(strArr[i].trim())));
       }
      }
     }
    }
    else {
     return "File can not be null";
    }
    httpClient.getParams().setContentCharset("UTF-8");
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode == 200) {
     strResponse = postMethod.getResponseBodyAsString();
    
    }
    return strResponse;
   } catch (Exception e){
    throw e;
   }
   finally
   {
    postMethod.releaseConnection();
   }
}
/**
* @category 发送邮件信息
* @param strUrl
* @param sysID
* @param pass
* @param from
* @param to
* @param title
* @param level
* @param body
* @param attachments
* @return 正常返回 200
* @throws Exception
*/
public String postMessage(String strUrl,String sysID,String pass,String from,String to,String title,String level,String body,String attachments) throws Exception
{
   HttpClient httpClient = new HttpClient();
   String responseBody="";
   PostMethod postMethod = new PostMethod(strUrl.trim());
   try {
    NameValuePair[] nameValuePairs ={new NameValuePair("SysID",sysID),
      new NameValuePair("Pass",pass),new NameValuePair("From",from),
      new NameValuePair("To",to),new NameValuePair("Title",title),
      new NameValuePair("Level",level),new NameValuePair("Body",body),
      new NameValuePair("Attachments",attachments)};
    postMethod.setRequestBody(nameValuePairs);
    httpClient.getParams().setContentCharset("UTF-8");
    int status = httpClient.executeMethod(postMethod);
    if (status == 200) {
     responseBody =postMethod.getResponseBodyAsString();
    }
    return responseBody;
   } catch (Exception e) {
    throw e;
   }
   finally
   {
    postMethod.releaseConnection();
   }
}


public static void main(String[] args) {
   HttpClientUtile testSendData = new HttpClientUtile();
   try {
    String sendMail = testSendData.sendMail("http://localhost:8080/HttpClientWeb/receive");  
    System.out.println("sendMail:"+sendMail);
    System.out.println(testSendData.uploadFiles("http://localhost:8080/HttpClientWeb/upload","D:/blackblack/com_plazmic_theme_BBglass_8x_4_5_by0901006.cod"));
    System.out.println(testSendData.uploadFiles("http://localhost:8080/HttpClientWeb/upload",new String[]{"D:/blackblack/com_plazmic_theme_BBglass_8x_4_5_by0901006.cod"}));
    String strPostMessage = testSendData.postMessage("http://localhost:8080/HttpClientWeb/receive", "dddddd", "pass", "from", "to", "title", "level", "body", "attachments");
    System.out.println("strPostMessage:"+strPostMessage);
    String strUploadFile = testSendData.uploadFiles("http://localhost:8080/HttpClientWeb/upload", "D:/blackblack/com_plazmic_theme_BBglass_8x_4_5_by0901006.cod");
    System.out.println("strUploadFile:"+strUploadFile);
   } catch (Exception e) {
    e.printStackTrace();
   }
}
}


注:上面的类中有测试的main方法,重新设置参数就可以进行运行测试


服务端处理:这里我写了两个servlet,一个处理文件上传,一个处理表单数据,另外,我实验的结果是上传文件的提交不能提交表单数据,在serlet中获取不到提交的数据,请大家再实验一下。

文件上传servlet:


‍package com.httpClient.servlet;

import java.io.File;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

public class UploadFileServ extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
   doPost(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
   try {
    String strFileFolder = "C:\\TempFolder";
    File file = new File(strFileFolder);
    if (!file.exists()) {
     file.mkdirs();
    }
    DiskFileUpload diskFileUpload = new DiskFileUpload();
    ///设置可上传文件的最大尺寸
    diskFileUpload.setSizeMax(1234556677);
    //设置缓冲区大小,这里是2kb
    diskFileUpload.setSizeThreshold(2048);
    //设置临时目录
    diskFileUpload.setRepositoryPath(strFileFolder);
    //获取所有文件
    List listFiles = diskFileUpload.parseRequest(req);
    if (null != listFiles && listFiles.size()>0) {
     for (int i = 0; i <listFiles.size(); i++) {
      FileItem fileItem = (FileItem)listFiles.get(i);
      if (null!= fileItem.getName()) {
       File saveFile = new File(strFileFolder,fileItem.getName());
       fileItem.write(saveFile);
      }
     }
    }
    PrintWriter out = resp.getWriter();
    out.write("You are success!");
    out.flush();
    out.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
}

}
表单提交处理servlet:


‍package com.httpClient.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

public class ReceivServ extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
   doPost(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
   try {
    String from = req.getParameter("From");
    PrintWriter out = resp.getWriter();
    out.write("You are success!"+from);
    out.flush();
    out.close();
   } catch (Exception e) {
    e.printStackTrace();
   }
}

}



xml配置:


<servlet>
   <servlet-name>responseServ</servlet-name>
   <servlet-class>com.httpClient.servlet.ReceivServ</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>responseServ</servlet-name>
   <url-pattern>/receive</url-pattern>
</servlet-mapping>
<servlet>
   <servlet-name>uploadServ</servlet-name>
   <servlet-class>com.httpClient.servlet.UploadFileServ</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>uploadServ</servlet-name>
   <url-pattern>/upload</url-pattern>
</servlet-mapping>
0 0
原创粉丝点击