steps

Empty InputStream in grails controller w/ Java client/URLCon

Jul 6th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. In controller "UploadController.groovy"
  2. -----------------------------------------------
  3.  
  4. def test() {
  5.     InputStream inStream = request.inputStream
  6.    
  7.     if(inStream != null) {
  8.         int read = 0;
  9.         byte[] buffer = new byte[4096];
  10.         long total = 0;
  11.        
  12.         println "Start reading"
  13.        
  14.         while((read = inStream.read(buffer)) != -1) {
  15.             println "Read " + read + " bytes from input stream buffer"      //<-- this is NEVER called
  16.         }      
  17.        
  18.         println "Reading finished"
  19.         println "Read a total of " + total + " bytes"   // <-- 'total' will always be 0 (zero)
  20.     } else {
  21.         println "Input Stream is null"      // <-- This is NEVER called
  22.     }
  23. }
  24.  
  25.  
  26. In Java client
  27. -----------------------------------------------
  28.  
  29. public void connect() {
  30.     final URL url = new URL("myserveraddress");
  31.     final byte[] message = "someMessage".getBytes();        // Any byte[] - will be a file one day
  32.     HttpURLConnection connection = url.openConnection();
  33.     connection.setRequestMethod("GET");                     // other methods - same result
  34.    
  35.     // Write message
  36.     DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  37.     out.writeBytes(message);
  38.     out.flush();
  39.     out.close();
  40.    
  41.     // Actually connect
  42.     connection.connect();                                   // is this placed correctly?
  43.    
  44.     // Get response
  45.     BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  46.    
  47.     String line = null;
  48.     while((line = in.readLine()) != null) {
  49.         System.out.println(line);                   // Prints the whole server response as expected
  50.     }
  51.    
  52.     in.close();
  53.    
  54. }
Add Comment
Please, Sign In to add comment