httpclient 上传文件

akarta的httpclient3.1是最新版本,项目中需要用程序模拟浏览器的GET和POST动作。在使用过程中遇到不少问题。
1. 带附件的POST提交
    最开始都是使用MultipartPostMethod这个类,现在已经废弃这个类了。API说明: Deprecated. Use MultipartRequestEntity in conjunction with PostMethod instead. 使用PostMethod可以实现的功能,就没有必要再弄一个MultipartPostMethod了。下面是一段最简单的示例:
PostMethod post = new PostMethod();
        NameValuePair[] pairs
= new NameValuePair[ 2 ];
        pairs[
0 ] = new NameValuePair( " para1 " , " value1 " );
        pairs[
0 ] = new NameValuePair( " para2 " , " value2 " );
        post.setRequestBody(pairs);
        HttpClient client
= new HttpClient();
       
try {
            client.executeMethod(post);
        }
catch (HttpException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }

   这是针对一般的form形式的提交,而且这个form里面不带附件的。如果带附件,那么这种方法就不起作用,附件上传的参数和普通参数无法一同在服务器获取到。org.apache.commons.httpclient.methods.multipart 这个包就是为处理文件上传这种多形式参数的情况的。最主要的类是Part(代表一种post object),它有二个比较重要的子类:FilePart和StringPart,一个是文件的参数,另一个就是普通的文本参数。它的典型使用方法如下:

String url = " http://localhost:8080/HttpTest/Test " ;
         PostMethod postMethod
= new PostMethod(url);
        
         StringPart sp
= new StringPart( " TEXT " , " testValue " );
         FilePart fp
= new FilePart( " file " , " test.txt " , new File( " ./temp/test.txt " ));
        
         MultipartRequestEntity mrp
= new MultipartRequestEntity( new Part[] {sp, fp} , postMethod
                 .getParams());
         postMethod.setRequestEntity(mrp);
        
        
// 执行postMethod
         HttpClient httpClient = new HttpClient();
        
try {
            httpClient.executeMethod(postMethod);
        }
catch (HttpException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }

    在第二行PostMethod postMethod = new  PostMethod();后面,有人说需要使用postMehtod.setRequestHeader("Content-type",  "multipart/form-data");  Content-type的请求类型进行更改。但是我在使用过程没有加上这一句,查了一下httpCleint的默认Content-type是application/octet-stream。应该是没有影响的。对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装,就是上面的用法。

2.  参数中文的处理问题
    httpclient的默认编码都是ISO-8859-1,那肯定就无法支持中文参数了。引用一下这篇文章:http://thinkbase.net/w/main/Wiki?HttpClient+POST+%E7%9A%84+UTF-8+%E7%BC%96%E7%A0%81%E9%97%AE%E9%A2%98,按照作者的说法,就可以正常解决中文编码的问题。其中最关键的是修改EncodingUtil这个类的一个方法实现。另外,FilePart和StringPart的构造方法都有一个带编码指定的参数,为了减少问题的出现,建议所有的都带上统一的编码,包括postMethod.getParams()。示例如下:

String url = " http://localhost:8080/HttpTest/Test " ;
         PostMethod postMethod
= new PostMethod(url);
        
         StringPart sp
= new StringPart( " TEXT " , " testValue " , " GB2312 " );
         FilePart fp
= new FilePart( " file " , " test.txt " , new File( " ./temp/test.txt " ), null , " GB2312 " );
        
         postMethod.getParams().setContentCharset(
" GB2312 " );
         MultipartRequestEntity mrp
= new MultipartRequestEntity( new Part[] {sp, fp} , postMethod
                 .getParams());
         postMethod.setRequestEntity(mrp);
        
        
// 执行postMethod
         HttpClient httpClient = new HttpClient();
        
try {
            httpClient.executeMethod(postMethod);
        }
catch (HttpException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }

httpclient笔记(二)

不多说了,直接上示例:

A服务器:

msURL为:http://192.168.7.203:8080

Java代码
  1. /**
  2.      * 发送文件到另一台服务器B
  3.      *
  4.      * @param File file 附件
  5.      * @param serviceType服务类型
  6.      * @param spId id
  7.      * @return
  8.      */ 
  9.     public String sendApply(File file, String serviceType, String spId) { 
  10.         String fromAgentResult = ""
  11.         HttpClient client = new HttpClient(); 
  12.         PostMethod filePost = new PostMethod(msUrl+"?serviceType="+serviceType+"&spId="+spId+"&type=menu"); 
  13. //       MultipartPostMethod filePost = new MultipartPostMethod(msUrl); 
  14.         // 若上传的文件比较大 , 可在此设置最大的连接超时时间  
  15.          client.getHttpConnectionManager(). getParams().setConnectionTimeout(8000);   
  16.  
  17.         try
  18.  
  19.             FilePart fp = new FilePart(file.getName(), file); 
  20.             MultipartRequestEntity mrp= new MultipartRequestEntity(new Part[]{fp}, filePost.getParams()); 
  21.             filePost.setRequestEntity(mrp); 
  22.  
  23.             //使用系统提供的默认的恢复策略 
  24.             filePost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
  25.                 new DefaultHttpMethodRetryHandler()); 
  26.  
  27.             int httpStat = client.executeMethod(filePost); 
  28.             System.out.println("httpStat----"+httpStat); 
  29.             if (!(httpStat == HttpStatus.SC_OK)) { 
  30.                 fromAgentResult = "connected fail:" + httpStat; 
  31.             } else if (httpStat == HttpStatus.SC_OK) { 
  32.                  
  33.                 try
  34.                     DocumentBuilderFactory factory = DocumentBuilderFactory 
  35.                             .newInstance(); 
  36.                     DocumentBuilder builder = factory.newDocumentBuilder(); 
  37.                     Document doc = builder 
  38.                             .parse(filePost.getResponseBodyAsStream()); 
  39.                     doc.normalize(); 
  40.                     // NodeList optypeNL= doc.getElementsByTagName("optype"); 
  41.                     NodeList resultNL = doc.getElementsByTagName("result"); 
  42.                     // fromAgentOptype= 
  43.                     // optypeNL.item(0).getFirstChild().getNodeValue(); 
  44.                     fromAgentResult = resultNL.item(0).getFirstChild() 
  45.                             .getNodeValue(); 
  46.                     System.out.println("发送请求完毕,接收状态:"+fromAgentResult); 
  47.                 } catch (Exception e) { 
  48.                     e.printStackTrace(); 
  49.                 } 
  50.             } 
  51.         } catch (HttpException e) { 
  52.             // TODO Auto-generated catch block 
  53.             e.printStackTrace(); 
  54.         } catch (IOException e) { 
  55.             // TODO Auto-generated catch block 
  56.             e.printStackTrace(); 
  57.         } 
  58.         filePost.releaseConnection(); 
  59.         return fromAgentResult; 
  60.     } 
  1. /**
  2.      * 发送文件到另一台服务器B
  3.      *
  4.      * @param File file 附件
  5.      * @param serviceType服务类型
  6.      * @param spId id
  7.      * @return
  8.      */ 
  9.     public String sendApply(File file, String serviceType, String spId) { 
  10.         String fromAgentResult = ""
  11.         HttpClient client = new HttpClient(); 
  12.         PostMethod filePost = new PostMethod(msUrl+"?serviceType="+serviceType+"&spId="+spId+"&type=menu"); 
  13. //       MultipartPostMethod filePost = new MultipartPostMethod(msUrl); 
  14.         // 若上传的文件比较大 , 可在此设置最大的连接超时时间  
  15.          client.getHttpConnectionManager(). getParams().setConnectionTimeout(8000);   
  16.  
  17.         try
  18.  
  19.             FilePart fp = new FilePart(file.getName(), file); 
  20.             MultipartRequestEntity mrp= new MultipartRequestEntity(new Part[]{fp}, filePost.getParams()); 
  21.             filePost.setRequestEntity(mrp); 
  22.  
  23.             //使用系统提供的默认的恢复策略 
  24.             filePost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
  25.                 new DefaultHttpMethodRetryHandler()); 
  26.  
  27.             int httpStat = client.executeMethod(filePost); 
  28.             System.out.println("httpStat----"+httpStat); 
  29.             if (!(httpStat == HttpStatus.SC_OK)) { 
  30.                 fromAgentResult = "connected fail:" + httpStat; 
  31.             } else if (httpStat == HttpStatus.SC_OK) { 
  32.                  
  33.                 try
  34.                     DocumentBuilderFactory factory = DocumentBuilderFactory 
  35.                             .newInstance(); 
  36.                     DocumentBuilder builder = factory.newDocumentBuilder(); 
  37.                     Document doc = builder 
  38.                             .parse(filePost.getResponseBodyAsStream()); 
  39.                     doc.normalize(); 
  40.                     // NodeList optypeNL= doc.getElementsByTagName("optype"); 
  41.                     NodeList resultNL = doc.getElementsByTagName("result"); 
  42.                     // fromAgentOptype= 
  43.                     // optypeNL.item(0).getFirstChild().getNodeValue(); 
  44.                     fromAgentResult = resultNL.item(0).getFirstChild() 
  45.                             .getNodeValue(); 
  46.                     System.out.println("发送请求完毕,接收状态:"+fromAgentResult); 
  47.                 } catch (Exception e) { 
  48.                     e.printStackTrace(); 
  49.                 } 
  50.             } 
  51.         } catch (HttpException e) { 
  52.             // TODO Auto-generated catch block 
  53.             e.printStackTrace(); 
  54.         } catch (IOException e) { 
  55.             // TODO Auto-generated catch block 
  56.             e.printStackTrace(); 
  57.         } 
  58.         filePost.releaseConnection(); 
  59.         return fromAgentResult; 
  60.     } 
/**
	 * 发送文件到另一台服务器B
	 * 
	 * @param File file 附件
	 * @param serviceType服务类型
	 * @param spId id
	 * @return
	 */
	public String sendApply(File file, String serviceType, String spId) {
		String fromAgentResult = "";
		HttpClient client = new HttpClient();
		PostMethod filePost = new PostMethod(msUrl+"?serviceType="+serviceType+"&spId="+spId+"&type=menu");
//		 MultipartPostMethod filePost = new MultipartPostMethod(msUrl);
		// 若上传的文件比较大 , 可在此设置最大的连接超时时间 
		 client.getHttpConnectionManager(). getParams().setConnectionTimeout(8000);  

		try {

			FilePart fp = new FilePart(file.getName(), file);
			MultipartRequestEntity mrp= new MultipartRequestEntity(new Part[]{fp}, filePost.getParams());
			filePost.setRequestEntity(mrp);

			//使用系统提供的默认的恢复策略
			filePost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
			    new DefaultHttpMethodRetryHandler());

			int httpStat = client.executeMethod(filePost);
			System.out.println("httpStat----"+httpStat);
			if (!(httpStat == HttpStatus.SC_OK)) {
				fromAgentResult = "connected fail:" + httpStat;
			} else if (httpStat == HttpStatus.SC_OK) {
				
				try {
					DocumentBuilderFactory factory = DocumentBuilderFactory
							.newInstance();
					DocumentBuilder builder = factory.newDocumentBuilder();
					Document doc = builder
							.parse(filePost.getResponseBodyAsStream());
					doc.normalize();
					// NodeList optypeNL= doc.getElementsByTagName("optype");
					NodeList resultNL = doc.getElementsByTagName("result");
					// fromAgentOptype=
					// optypeNL.item(0).getFirstChild().getNodeValue();
					fromAgentResult = resultNL.item(0).getFirstChild()
							.getNodeValue();
					System.out.println("发送请求完毕,接收状态:"+fromAgentResult);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		filePost.releaseConnection();
		return fromAgentResult;
	}

B服务器接收:

Java代码
  1. boolean bl = false
  2.     System.out.println("接收文件开始--------------"); 
  3.     String serviceType = request.getParameter("serviceType"); 
  4.     String spId = request.getParameter("spId"); 
  5.     String type = request.getParameter("type"); 
  6.     if (type.equals("menu")) { 
  7.  
  8.         DiskFileUpload fu = new DiskFileUpload(); 
  9.         fu.setSizeMax(1000000); 
  10.  
  11.         List fileItems; 
  12.  
  13.         try
  14.             fileItems = fu.parseRequest(request); 
  15.             Iterator itr = fileItems.iterator(); 
  16.             while (itr.hasNext()) { 
  17.                 FileItem fi = (FileItem) itr.next(); 
  18.  
  19.                 if (!fi.isFormField()) { 
  20.                     System.out.println("/nNAME: " + fi.getName()); 
  21.                     System.out.println("SIZE: " + fi.getSize()); 
  22.                     try
  23.                         String newFileName = msu.updateName(Integer 
  24.                                 .parseInt(serviceType), spId); 
  25.                         System.out.println("newFileName---------------" 
  26.                                 + newFileName); 
  27.                         File fNew = new File(applyFilePath, newFileName); 
  28.                         fi.write(fNew); 
  29.                         bl = msu.acceptApply(Integer.parseInt(serviceType), 
  30.                                 spId, newFileName); 
  31.  
  32.                         System.out.println(fNew.getAbsolutePath()); 
  33.  
  34.                     } catch (Exception e) { 
  35.                         // TODO Auto-generated catch block 
  36.                         e.printStackTrace(); 
  37.                     } 
  38.                 } else
  39.                     System.out.println("Field =" + fi.getFieldName()); 
  40.                 } 
  41.             } 
  42.  
  43.         } catch (FileUploadException e1) { 
  44.             // TODO Auto-generated catch block 
  45.             e1.printStackTrace(); 
  46.         } 
  47.     } 
  1. boolean bl = false
  2.     System.out.println("接收文件开始--------------"); 
  3.     String serviceType = request.getParameter("serviceType"); 
  4.     String spId = request.getParameter("spId"); 
  5.     String type = request.getParameter("type"); 
  6.     if (type.equals("menu")) { 
  7.  
  8.         DiskFileUpload fu = new DiskFileUpload(); 
  9.         fu.setSizeMax(1000000); 
  10.  
  11.         List fileItems; 
  12.  
  13.         try
  14.             fileItems = fu.parseRequest(request); 
  15.             Iterator itr = fileItems.iterator(); 
  16.             while (itr.hasNext()) { 
  17.                 FileItem fi = (FileItem) itr.next(); 
  18.  
  19.                 if (!fi.isFormField()) { 
  20.                     System.out.println("/nNAME: " + fi.getName()); 
  21.                     System.out.println("SIZE: " + fi.getSize()); 
  22.                     try
  23.                         String newFileName = msu.updateName(Integer 
  24.                                 .parseInt(serviceType), spId); 
  25.                         System.out.println("newFileName---------------" 
  26.                                 + newFileName); 
  27.                         File fNew = new File(applyFilePath, newFileName); 
  28.                         fi.write(fNew); 
  29.                         bl = msu.acceptApply(Integer.parseInt(serviceType), 
  30.                                 spId, newFileName); 
  31.  
  32.                         System.out.println(fNew.getAbsolutePath()); 
  33.  
  34.                     } catch (Exception e) { 
  35.                         // TODO Auto-generated catch block 
  36.                         e.printStackTrace(); 
  37.                     } 
  38.                 } else
  39.                     System.out.println("Field =" + fi.getFieldName()); 
  40.                 } 
  41.             } 
  42.  
  43.         } catch (FileUploadException e1) { 
  44.             // TODO Auto-generated catch block 
  45.             e1.printStackTrace(); 
  46.         } 
  47.     } 
	boolean bl = false;
		System.out.println("接收文件开始--------------");
		String serviceType = request.getParameter("serviceType");
		String spId = request.getParameter("spId");
		String type = request.getParameter("type");
		if (type.equals("menu")) {

			DiskFileUpload fu = new DiskFileUpload();
			fu.setSizeMax(1000000);

			List fileItems;

			try {
				fileItems = fu.parseRequest(request);
				Iterator itr = fileItems.iterator();
				while (itr.hasNext()) {
					FileItem fi = (FileItem) itr.next();

					if (!fi.isFormField()) {
						System.out.println("/nNAME: " + fi.getName());
						System.out.println("SIZE: " + fi.getSize());
						try {
							String newFileName = msu.updateName(Integer
									.parseInt(serviceType), spId);
							System.out.println("newFileName---------------"
									+ newFileName);
							File fNew = new File(applyFilePath, newFileName);
							fi.write(fNew);
							bl = msu.acceptApply(Integer.parseInt(serviceType),
									spId, newFileName);

							System.out.println(fNew.getAbsolutePath());

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						System.out.println("Field =" + fi.getFieldName());
					}
				}

			} catch (FileUploadException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
Java代码
  1. //下面是返回执行结果 
  1. //下面是返回执行结果 
//下面是返回执行结果
Java代码
  1.   msu.responseToAS(response, bl); 
  2.   System.out.println("接收申请处理完毕,状态:" + bl); 
  3.   return null
  1.   msu.responseToAS(response, bl); 
  2.   System.out.println("接收申请处理完毕,状态:" + bl); 
  3.   return null
  msu.responseToAS(response, bl);
  System.out.println("接收申请处理完毕,状态:" + bl);
  return null;
Java代码
  1. //msu.responseToAS 
  1. //msu.responseToAS 
//msu.responseToAS
Java代码
  1. public void responseToAS(HttpServletResponse response, boolean synSuccess) { 
  2.   try
  3.    PrintWriter out = response.getWriter(); 
  4.    if (synSuccess) 
  5.     out 
  6.       .println("<?xml version=/"1.0/" encoding=/"UTF-8/"?><root><result>ok</result></root>"); 
  7.    else 
  8.     out 
  9.       .println("<?xml version=/"1.0/" encoding=/"UTF-8/"?><root><result>fail</result></root>"); 
  10.   } catch (IOException e) { 
  11.    e.printStackTrace(); 
  12.    System.out.println("responseToAS--error"); 
  13.   } 

http://www.xd-tech.com.cn/blog/article.asp?id=34一般的情况下我们都是使用IE或者Navigator浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据等等。所访问的这些页面有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如HTTPS。目前我们使用的浏览器处理这些情况都不会构成问题。不过你可能在某些时候需要通过程序来访问这样的一些页面,比如从别人的网页中“偷”一些数据;利用某些站点提供的页面来完成某种功能,例如说我们想知道某个手机号码的归属地而我们自己又没有这样的数据,因此只好借助其他公司已有的网站来完成这个功能,这个时候我们需要向网页提交手机号码并从返回的页面中解析出我们想要的数据来。如果对方仅仅是一个很简单的页面,那我们的程序会很简单,本文也就没有必要大张旗鼓的在这里浪费口舌。但是考虑到一些服务授权的问题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉及到COOKIE问题的处理。我们知道目前流行的***页技术例如ASP、JSP无不是通过COOKIE来处理会话信息的。为了使我们的程序能使用别人所提供的服务页面,就要求程序首先登录后再访问服务页面,这过程就需要自行处理cookie,想想当你用java.net.HttpURLConnection来完成这些功能时是多么恐怖的事情啊!况且这仅仅是我们所说的顽固的WEB服务器中的一个很常见的“顽固”!再有如通过HTTP来上传文件呢?不需要头疼,这些问题有了“它”就很容易解决了! 我们不可能列举所有可能的顽固,我们会针对几种最常见的问题进行处理。当然了,正如前面说到的,如果我们自己使用java.net.HttpURLConnection来搞定这些问题是很恐怖的事情,因此在开始之前我们先要介绍一下一个开放源码的项目,这个项目就是Apache开源组织中的httpclient,它隶属于Jakarta的commons项目,目前的版本是2.0RC2。commons下本来已经有一个net的子项目,但是又把httpclient单独提出来,可见http服务器的访问绝非易事。Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给httpclient替你完成。本文会针对我们在编写HTTP客户端程序时经常碰到的几个问题进行分别介绍如何使用httpclient来解决它们,为了让读者更快的熟悉这个项目我们最开始先给出一个简单的例子来读取一个网页的内容,然后循序渐进解决掉前进中的所形侍狻?/font>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值