在STRUTS中如何通过request获取从HttpURLConnection写出的流对象 .

最近在一个项目中,需要从HttpURLConnection中写出流,在STRUTS中通过request获取流对象,但是,不管怎么样操作,在STRUTS的request中就是不能获取对应的流,很郁闷的说,之后找到了关键点,因为流写出的时候设置了表单提交的形式,导致STRUTS中获取流时出现了问题,struts对没有指定content-type的request请求,封装时候作了一些处理,导致无法在Action中获取request.getInputStream() 和 request.getReader()。 详细可以查看代码例子。

1. sendPost方法,从本地中获取流,写入到相应的url链接中:

   (重点):            

            //需要传递流时,一定要添加的参数,而且ACTION中通过request.getInputStream获取流的情况下,也必须添加该参数
            conn.setRequestProperty("content-type", "text/html");      //直接传递流对象   

           //以下的则是通过form组件的形式来传递流对象的,具体使用上网查看。 

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


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

转载于:https://my.oschina.net/u/219582/blog/59482

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值