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.   } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章