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>
分享到:
相关推荐
HttpClient 上传文件 Servlet 处理文件上传 commons-fileupload 处理文件上传 commons-fileupload 处理文件上传,在struts中可以不用对应actionform,在jsp,servelet中应用都很方便
2. **配置Servlet**:在`web.xml`中配置Servlet,处理POST请求并指定文件上传路径。 ```xml <servlet> <servlet-name>FileUploadServlet</servlet-name> <servlet-class>...
在处理文件上传时,Servlet可以解析请求的多部分数据,提取出文件和其他参数。在Servlet 3.0及以上版本,可以直接使用`HttpServletRequest`的`getParts()`方法来获取上传的文件Part对象。 对于多文件参数上传,我们...
它提供了处理文件上传的简单接口和工具类,可以方便地集成到任何基于Servlet的Web应用程序中。 3. **commons-io-2.4.jar**:Apache Commons IO是处理输入/输出操作的库,提供了许多实用的工具方法和流处理类。它...
使用HttpClient与FileUpload库结合,可以实现从客户端到服务器端的完整文件上传流程。 总的来说,Apache FileUpload提供了处理HTTP文件上传的强大工具,无论你是处理小文件还是大文件,它都能提供合适的方法。同时...
Swing与Servlet通信是Java开发中常见的客户端-服务器交互方式,尤其在构建桌面应用程序与Web服务接口时。Swing作为Java的图形用户界面(GUI)库,提供了丰富的组件和工具来创建美观的桌面应用,而Servlet是Java Web...
在Java中,处理文件上传的核心库是Apache Commons FileUpload和Servlet API。Apache Commons FileUpload是一个用于处理多部分请求的库,它可以从请求中解析出单独的文件项。Servlet API则提供了处理HTTP请求的基础...
以下是一个简单的Servlet示例,用于处理文件上传: ```java @WebServlet("/upload") public class UploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse ...
在实际应用中,当我们需要同时发送普通参数和文件到服务器时,HttpClient是一个理想的选择,因为它支持多部分请求,这是上传文件所必需的。 在HTTP中,POST请求通常用于向服务器提交数据,包括表单数据、文件等。...
在Java中,实现基于HTTP的文件上传至服务器通常涉及到Servlet技术。Servlet是Java提供的一种用于扩展Web服务器...在实际应用中,还可以使用Apache HttpClient库或Spring框架的MultipartFile接口来简化文件上传操作。
文件上传是Web应用程序中常见的操作,它涉及到客户端与服务器之间的数据传输。在这个场景下,"文件上传源码 客户端服务端" 提供了实现这一功能的代码示例,包括客户端和服务端两部分,使用的技术有Socket和...
在Web应用程序中,通常使用Servlet API来处理服务器端的文件上传。`HttpServletRequest`对象提供了`getParts()`方法,可以用来获取上传的文件部分。你需要在Servlet中解析这些部分并保存到服务器的文件系统、数据库...
6. **客户端实现**:在客户端(如网页、移动应用)中,通常会使用JavaScript的FormData对象来处理文件上传,它可以将文件添加到POST请求中。对于原生应用,如Android或iOS,会使用相应的API来实现文件选择和HTTP请求...
总结,"文件上传工具,批量导入代码"涉及到的技术点包括:Java文件操作,HTTP请求处理,多线程与并发,Servlet处理文件上传,大文件流式处理,代码解析,实时通信以及安全防护。理解并掌握这些知识点,能够帮助...
在Android应用开发中,文件上传是一项常见的功能,尤其在社交、云存储或协作类应用中。本篇将详细讲解如何在Android中实现文件上传,并结合“亲测可用”的控件来探讨具体实践。 首先,我们需要了解Android中的文件...
3. **异常处理与进度条**: 在实际应用中,应处理可能出现的网络错误,并考虑提供一个进度条来展示文件上传进度。可以使用Swing的`javax.swing.ProgressMonitor`类来创建进度条,并更新其值来反映上传进度。 4. **...
2. **Servlet**:在传统的 Java Web 应用中,我们通常会使用 Servlet 来处理文件上传和下载。`javax.servlet.http.HttpServletRequest` 可以用来获取上传文件的信息,如文件名、大小等。`javax.servlet....
在Java后端开发中,`HttpClient`是一个非常重要的工具,用于执行HTTP请求。Apache HttpClient库提供了丰富的功能,...通过理解和熟练运用这些概念,你可以构建可靠的文件上传和下载功能,增强你的Java后端应用程序。
8. 进度条与用户体验:对于大文件上传,提供进度条显示能提升用户体验。这需要在客户端和服务端同步文件上传进度,可以利用JavaScript的XMLHttpRequest Level 2的progress事件,配合服务器端的状态更新实现。 总结...