4 Replies Latest reply: Feb 5, 2012 4:53 PM by EJP RSS

    Index Error When Communicating with PHP App From Java

    913905
      Hi,
      I have a simple PHP application that I'm using to practice using the Java URLConnection class.
      I'm using NetBeans 7.0.1 to develop and run the app.

      When I run my application I get the following error:
      Notice: Undefined index: string in C:\Apache\htdocs\reverse.php on line 4
      But when I use the debugger to run the file, it works fine! This is totally confusing. Please help -- I've been spending most of my time on this issue.
      Thanks

      Here is the PHP code:
      <?php
           
           date_default_timezone_set('UTC');
          $stringToReverse = $_POST['string'];
           echo "String to reverse: ".$stringToReverse."\n";
           
           $length = strlen($stringToReverse);
           
           echo "The string in reverse: \n";
           for ($i = $length-1; $i > -1; $i--)
           {
                echo $stringToReverse[$i];
           }
          echo " \ndone";
           
      ?>
      Here is my java app:
      import java.io.*;
      import java.net.*;
      
      public class Reverse {
          public static void main(String[] args) throws Exception 
          {
              try 
              {
                  String strToReverse = "able was I ere I saw elba";
                  String data = URLEncoder.encode("string", "UTF-8") + "=" + URLEncoder.encode(strToReverse, "UTF-8");
      
                  // Send data
                  URL url = new URL("http://localhost/reverse.php");
                  URLConnection conn = url.openConnection();
                  conn.setDoOutput(true);
                  conn.setDoInput(true);
                  OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                  wr.write(data);
                  wr.flush();
      
                  // Get the response
                  BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                  String line;
                  while ((line = rd.readLine()) != null) {
                      System.out.println(line);
                  }
                  wr.close();
                  rd.close();
              }
              catch(Exception ex) 
              {
                  System.out.println("Exception caught:\n"+ ex.toString());
              }
          }
      }