HttpClient应用 与 Servlet 处理文件上传

 
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 WPF 中使用 HttpClient文件时,需要对文件进行分块上,以避免一次性上文件导致的内存占用过高的问题。以下是一个示例代码: ```csharp using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; public async Task UploadLargeFile(string filePath, string apiUrl) { try { const int chunkSize = 8192; // 每个分块的大小,可以根据需要进行调整 using (var httpClient = new HttpClient()) { using (var fileStream = File.OpenRead(filePath)) { var totalChunks = (int)Math.Ceiling((double)fileStream.Length / chunkSize); for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { var buffer = new byte[chunkSize]; var bytesRead = fileStream.Read(buffer, 0, chunkSize); using (var content = new ByteArrayContent(buffer, 0, bytesRead)) { content.Headers.Add("Content-Type", "application/octet-stream"); content.Headers.Add("Content-Disposition", "attachment; filename=\"" + Path.GetFileName(filePath) + "\""); content.Headers.Add("X-Chunk-Index", chunkIndex.ToString()); content.Headers.Add("X-Total-Chunks", totalChunks.ToString()); var response = await httpClient.PostAsync(apiUrl, content); if (!response.IsSuccessStatusCode) { // 处理失败的逻辑 return; } } } } } // 文件完成 // 处理成功的逻辑 } catch (Exception ex) { // 异常处理 } } ``` 在这个示例中,我们将文件分为多个大小为 `chunkSize` 的块,然后逐个块进行上。每个块的内容会作为字节数组放入 `ByteArrayContent` 中,并通过请求头递了分块相关的信息(当前块的索引和总块数)。 请注意,在实际使用时,需要根据你的实际需求修改代码,例如调整分块大小、设置其他请求头或请求参数等。另外,还需要根据你的后端 API 的要求来处理的分块数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值