在STRUTS中如何經過request獲取從HttpURLConnection寫出的流對象 .

最近在一個項目中,須要從HttpURLConnection中寫出流,在STRUTS中經過request獲取流對象,可是,無論怎麼樣操做,在STRUTS的request中就是不能獲取對應的流,很鬱悶的說,以後找到了關鍵點,由於流寫出的時候設置了表單提交的形式,致使STRUTS中獲取流時出現了問題,struts對沒有指定content-type的request請求,封裝時候做了一些處理,致使沒法在Action中獲取request.getInputStream() 和 request.getReader()。 詳細能夠查看代碼例子。html

1. sendPost方法,從本地中獲取流,寫入到相應的url連接中:java

   (重點):            web

            //須要傳遞流時,必定要添加的參數,並且ACTION中經過request.getInputStream獲取流的狀況下,也必須添加該參數
            conn.setRequestProperty("content-type", "text/html");      //直接傳遞流對象   緩存

           //如下的則是經過form組件的形式來傳遞流對象的,具體使用上網查看。 dom

          conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString()); this


  1.     public static void main(String[] args) throws UnsupportedEncodingException {  
  2.            
  3. //      String url = "http://61.154.14.46:8080/exter.shtml?serviceType=1011";   
  4.         String url = "http://localhost:8080/webtest/servlet/URLTest?name=linlin";  
  5. //      String url = "http://localhost:8081/exter.shtml?serviceType=1022&menuId=4481&mobile=15806092760&text_data=linlinlin&imgName=testa.jpg";   
  6. //      getReturnData1(url);   
  7.         sendPost(url,null);  
  8.     }   
public static void main(String[] args) throws UnsupportedEncodingException { // String url = "http://61.154.14.46:8080/exter.shtml?serviceType=1011"; String url = "http://localhost:8080/webtest/servlet/URLTest?name=linlin"; // String url = "http://localhost:8081/exter.shtml?serviceType=1022&menuId=4481&mobile=15806092760&text_data=linlinlin&imgName=testa.jpg"; // getReturnData1(url); sendPost(url,null); }

  1. /** 
  2.    * 經過HTTP協議以POST形式發送指定文件至指定url 
  3.    * @param url 
  4.    * @throws IOException 
  5.    */  
  6.   public static void sendPost(String url,InputStream in) {  
  7.         
  8.     HttpURLConnection conn = null;  
  9.     OutputStreamWriter osw = null;  
  10.       try {  
  11.         File file = new File("D:/test2.jpg");  
  12.     if(!file.exists()) {  
  13.         try {  
  14.             file.createNewFile();  
  15.         } catch (IOException e) {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.           URL url1 = new URL(url);  
  20.           conn = (HttpURLConnection)url1.openConnection();  
  21.           conn.setReadTimeout(10000); // 緩存的最長時間   
  22.           conn.setDoInput(true);// 容許輸入   
  23.           conn.setDoOutput(true);// 容許輸出   
  24.           conn.setUseCaches(false); // 不容許使用緩存   
  25.           conn.setRequestMethod("POST");  
  26.           conn.setRequestProperty("Charsert""UTF-8");   
  27.           //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString());   
  28.           //須要傳遞流時,必定要添加的內容,並且ACTION中經過request.getInputStream獲取也必須添加該選項   
  29.           conn.setRequestProperty("content-type""text/html");   
  30.           OutputStream o = conn.getOutputStream();  
  31.         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
  32.         int BUFFER_SIZE = 1024;   
  33.         byte[] buf = new byte[BUFFER_SIZE];      
  34.         int size = 0;      
  35.         try {  
  36.             while ((size = bis.read(buf)) != -1)       
  37.                 o.write(buf, 0, size);  
  38.         } catch (IOException e) {  
  39.             e.printStackTrace();  
  40.         }      
  41.         finally {  
  42.             try {  
  43.                 bis.close();  
  44.                 o.close();  
  45.             } catch (IOException e) {  
  46.                 // TODO Auto-generated catch block   
  47.                 e.printStackTrace();  
  48.             }  
  49.         }   
  50.             
  51.           if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)  
  52.               System.out.println( "connect failed!");  
  53.       } catch (IOException e) {  
  54.           e.printStackTrace();  
  55.       }  
  56.       finally  
  57.       {  
  58.           if (osw != null)  
  59.               try {  
  60.                   osw.close() ;  
  61.               } catch (IOException e1) {  
  62.                   e1.printStackTrace();  
  63.               }  
  64.             
  65.           if (conn != null)  
  66.               conn.disconnect() ;  
  67.       }  
  68.   }  
/** * 經過HTTP協議以POST形式發送指定文件至指定url * @param url * @throws IOException */ public static void sendPost(String url,InputStream in) { HttpURLConnection conn = null; OutputStreamWriter osw = null; try { File file = new File("D:/test2.jpg"); if(!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } URL url1 = new URL(url); conn = (HttpURLConnection)url1.openConnection(); conn.setReadTimeout(10000); // 緩存的最長時間 conn.setDoInput(true);// 容許輸入 conn.setDoOutput(true);// 容許輸出 conn.setUseCaches(false); // 不容許使用緩存 conn.setRequestMethod("POST"); conn.setRequestProperty("Charsert", "UTF-8"); //conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + java.util.UUID.randomUUID().toString()); //須要傳遞流時,必定要添加的內容,並且ACTION中經過request.getInputStream獲取也必須添加該選項 conn.setRequestProperty("content-type", "text/html"); OutputStream o = conn.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; try { while ((size = bis.read(buf)) != -1) o.write(buf, 0, size); } catch (IOException e) { e.printStackTrace(); } finally { try { bis.close(); o.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) System.out.println( "connect failed!"); } catch (IOException e) { e.printStackTrace(); } finally { if (osw != null) try { osw.close() ; } catch (IOException e1) { e1.printStackTrace(); } if (conn != null) conn.disconnect() ; } }


2.  當按照以上方法寫出流時,就能夠在servlet或者action中獲取對應的流信息了,代碼以下:

  1. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  2.         throws ServletException, IOException {  
  3.   
  4.     response.setContentType("text/html");  
  5.     String s = request.getParameter("name");  
  6.     System.out.println("s22 is " + s);  
  7.       
  8.     InputStream in = request.getInputStream();  
  9.     if(in != null) {  
  10.         System.out.println("流不是空的。");  
  11.         this.writeInputStreamToFile(in);  
  12.          System.out.println("server time is " + new Date());  
  13.     } else {  
  14.         System.out.println("流是空的。");  
  15.     }  
  16.       
  17.       
  18.     PrintWriter out = response.getWriter();  
  19.     out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");  
  20.     out.println("<HTML>");  
  21.     out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");  
  22.     out.println("  <BODY>");  
  23.     out.print("    This is ");  
  24.     out.print(this.getClass());  
  25.     out.println(", using the POST method");  
  26.     out.println("  </BODY>");  
  27.     out.println("</HTML>");  
  28.     out.flush();  
  29.     out.close();  
  30. }  
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String s = request.getParameter("name"); System.out.println("s22 is " + s); InputStream in = request.getInputStream(); if(in != null) { System.out.println("流不是空的。"); this.writeInputStreamToFile(in); System.out.println("server time is " + new Date()); } else { System.out.println("流是空的。"); } PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); }
  1. private void writeInputStreamToFile(InputStream in) throws FileNotFoundException {  
  2.       
  3.     File file = new File("D:/test3.jpg");  
  4.     if(!file.exists()) {  
  5.         try {  
  6.             file.createNewFile();  
  7.         } catch (IOException e) {  
  8.             // TODO Auto-generated catch block   
  9.             e.printStackTrace();  
  10.         }  
  11.     }  
  12.       
  13.        FileOutputStream fos = new FileOutputStream(file);  
  14.     BufferedInputStream bis = new BufferedInputStream(in);  
  15.     int BUFFER_SIZE = 1024;   
  16.     byte[] buf = new byte[BUFFER_SIZE];      
  17.     int size = 0;      
  18.     try {  
  19.         while ((size = bis.read(buf)) != -1)       
  20.             fos.write(buf, 0, size);  
  21.     } catch (IOException e) {  
  22.         e.printStackTrace();  
  23.     }      
  24.     finally {  
  25.         try {  
  26.             bis.close();  
  27.             fos.close();  
  28.         } catch (IOException e) {  
  29.             // TODO Auto-generated catch block   
  30.             e.printStackTrace();  
  31.         }  
  32.     }   
  33.       
  34. }  
相關文章
相關標籤/搜索