1 2 Previous Next 16 Replies Latest reply on Jul 8, 2004 11:21 PM by SunForumsGuest7-MOS

    Writing URLConnections & CGI HELPPPPP!

    SunForumsGuest7-MOS
      Hi All,

      I am having serious problems trying to work out how to write to a URL. What I am
      trying to do is calculate how long it takes to upload data from an applet to a webserver.
      Ive got the download part working. I save the downloaded data into a buffer called 'data'.
      Then I use this same 'data' to write back to the webserver. Im not sure if I have to create a
      PHP/ Perl script to read the 'data' ?

      Thanks heaps. There are some inline comments which show where the
      main problem is:


      public double upload(){

      double u = 0.0;
      i1 = 10723844; // size of the mp3 file.

      System.out.println("Uploading...");
      try
      {
      long k = new Date().getTime(); // get start time

      URL uRL = new URL("http://www.myhome/outfile);
      URLConnection uRLConnection = uRL.openConnection();
      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setUseCaches(false);
      uRLConnection.setRequestProperty("Content-Type","audio/basic");
      DataOutputStream dataOutputStream = new DataOutputStream(uRLConnection.getOutputStream());

      // My problem is directly below. How can the contents of data which is data = new byte [1024000];
      // be written to a file on the webserver. The applet will be running from the same webserver that
      // I need to write to.

      // Can I write directly over the file "outfile" which is empty to start with? Or do I need to
      // have a PHP script that reads the 'data' from the application/ applet to a buffer then write this
      // data to a file?


      for (; i1 > 1024000; i1 -= 1024000)
      dataOutputStream.write(data,0,1024000);



      long i2 = new Date().getTime(); // get end time
      dataOutputStream.flush();
      dataOutputStream.close();

      long j2 = i2 - k;
      u = (double)(i1 * 8) / ((double)j2 / 1000.0) / 1000.0;
      upspeed = (long)u / 8;
      System.out.println(upspeed);
      }
      catch (IOException e1)
      {
      System.out.println("I/O Exception");
      }

      }
      }
        • 1. Re: Writing URLConnections & CGI HELPPPPP!
          SunForumsGuest7-MOS
          You will need to create an upload script of some sort on your web server, and create a second post request using a url connection and write the file to the outputstream of that connection.
          • 2. Re: Writing URLConnections & CGI HELPPPPP!
            SunForumsGuest7-MOS
            Im not sure why I would need to create a second post.

            the applet reads a file using URLConnection
            then creates an output stream which POST data to a CGI script.

            does anyone know where I can find some example code for this. Would
            it be best to write the script in PHP, Perl?

            Thanks

            • 3. Re: Writing URLConnections & CGI HELPPPPP!
              SunForumsGuest7-MOS

              Exactly

              U have a URL Connection established already with server, use this connection itself to send the data back.

              What u have to keep in mind is that

              1) The content-type should be mentioned right.

              2) Try to set the file name and the extension in the header so that in the server u can fetch the extension
              and save it in the same format. This helps in sending any kind of data and saving in the same format.

              3) Use any server scripts let it be perl, jsp, asp, servlet any thing u are convinient with and recieve the
              data and do the further processing.

              • 4. Re: Writing URLConnections & CGI HELPPPPP!
                798701
                I suppose serlank meant that you need to create a second request, POST one this time, so two in total...

                The "custom networking" trail in the java tutorial has an example of posting data to a server script:
                http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html

                The example CGI there is implemented in Perl but you might as well do it in PHP, whatever you prefer.

                Here's another example:
                http://javaalmanac.com/egs/java.net/Post.html
                Here's yet another:
                http://www.javaworld.com/javaworld/javatips/jw-javatip34.html
                • 5. Re: Writing URLConnections & CGI HELPPPPP!
                  SunForumsGuest7-MOS
                  thanks vinuth,

                  would u know where i could source a php script that accepts data from a URLConnection.
                  i cant find any examples of how these two would talk.

                  thanks tendulkar!
                  • 6. Re: Writing URLConnections & CGI HELPPPPP!
                    798701
                    Since PHP maps request parameters directly to variables, the example "backwards" Perl script in the custom networking tutorial above would be this short in PHP:
                    <?= strrev($string) ?>
                    Communication with the server would be exactly same.
                    • 7. Re: Writing URLConnections & CGI HELPPPPP!
                      SunForumsGuest7-MOS

                      Hey there is no contact between ur applet and php at all.

                      Applet talks to webserver and webserver will send the request to PHP scripts.

                      So u dont have to think of how to get data from url connection.

                      All the webservers will provide api's to read the data from the input stream and read the header aswell

                      use those api's in ur PHP script to read the data and u will get back the data sent by applet.

                      Do the further processing. some of the example api's might be like getHostName(), getUserAgent(),

                      getHeader() etc. use the necessary api's ur work will be done.

                      Regarding the example might be if u search in the net u will find many and I dont know PHP

                      • 8. Re: Writing URLConnections & CGI HELPPPPP!
                        SunForumsGuest7-MOS
                        I suppose serlank meant that you need to create a second request, POST one this time, so two in total...
                        Yup, that's exactly what I meant. You can't make a request, read the resonse, and then write back to the outputstream of that url connection. That's not how http works.
                        • 9. Re: Writing URLConnections & CGI HELPPPPP!
                          SunForumsGuest7-MOS
                          ok so if im posting a ab = new byte [1024000];
                          which is a 1MB mp3 file how does the server side CGI look like
                          would that be all I need to write the file from the applet to the
                          php script and then onto the Output.mp3 file. Someone mentioned I
                          need to grab the POST? wont PHP pick up that Im passing 'ab'.

                          sorry guys im new to network programming.


                          ---------------------------------------------------
                          <?
                          echo ($ab) > "Outputfile.mp3"
                          ?>
                          • 10. Re: Writing URLConnections & CGI HELPPPPP!
                            SunForumsGuest7-MOS
                            I have no idea how to do uploads in php. Maybe do a search?
                            • 11. Re: Writing URLConnections & CGI HELPPPPP!
                              SunForumsGuest7-MOS
                              Here is some example code for this
                              import java.net.*;
                              import java.io.*;
                              
                              public class Poster {
                                  public static void main (String args[]) throws Exception{
                              
                              
                                      String fileToSend = "html.rar";         //Should be a existing file
                                      String fileNameToSaveOnServer = "test.rar";   //Should be a valid file name in the servers File System
                              
                              
                                      //This is the connectio the PERL script 
                                      //Here the script is hosted on the IIS server running my PC "cmbtrifs2"
                                      URL u = new URL("http://cmbtrifs2/j2pl/upload.pl?" + fileNameToSaveOnServer);
                                      URLConnection c = u.openConnection();
                                      c.setDoInput(true);
                                      c.setDoOutput(true);
                              
                                      OutputStream os = c.getOutputStream();
                              
                                      //Read and send the file
                                      FileInputStream fis = new FileInputStream(fileToSend);
                                      int count;
                                      byte b[] = new byte[1024];
                                      while ((count = fis.read(b))!=-1) {
                                        os.write(b,0,count);
                                      }
                                      //Close the output Stream
                                      os.close();
                              
                              
                                      //Read the response of the server
                                      DataInputStream dis =new DataInputStream(c.getInputStream()); 
                                      String line;
                                      while ((line = dis.readLine())!=null) {
                                          System.out.println(line);
                                      }
                                      dis.close();
                                  }
                              }
                              Here is the Perl Script to accept the data send by the above Java Program
                              #!/urs/bin/perl
                              
                              #/*
                              # Here is the perl code 
                              # This file should be hosted in a PERL-CGI supported web server
                              # And it should have the permission to be executed and write to the disk
                              #
                              #
                              #
                              #*/
                              
                              #// Switching the Standerd Input to the binary Datatransfer mode
                              binmode STDIN;
                              
                              #//  Reading the Data send by the client
                              read STDIN,$var,$ENV{'CONTENT_LENGTH'};
                              
                              #// retriving the filename to save from the Query String
                              my $fileNameToSave = $ENV{'QUERY_STRING'};
                              
                              #// Opening the file for writing
                              open(FILEHANDLE, ">$fileNameToSave");
                              
                              #// Switching to the binary Datatransfer mode
                              binmode FILEHANDLE;
                              
                              #// Writing Data
                              print FILEHANDLE $var;
                              #// Closing The File
                              close(FILEHANDLE);
                              
                              #// Sending a valid response to the client through the web server
                              print "Cache-Control: no-cache\n";
                              print "Content-Type: text/html\n\n";
                              
                              print "<pre>\n";
                              print "Got The File. Thankx\n";
                              print "</pre>\n";
                              • 12. Re: Writing URLConnections & CGI HELPPPPP!
                                SunForumsGuest7-MOS
                                Thanks for the last post. You win duke dollars for sure.
                                Just one thing tho. After I compiled the source I get an error

                                Exception in thread "main" java.io.IOException: Server returned HTTP response code: 405 for URL: http://xxx.xxx.xxx.xxx/Poster.pl?test.rar
                                at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:789)
                                at Poster.main(Poster.java:33)

                                405 means method not allowed. I am running the above piece of code on the same machine
                                that the files and perl script reside on.

                                once working i will convert the java application to an applet.

                                So my question is how do I allow permission for this method. I have even chmod to all the
                                associated files to 777.


                                • 13. Re: Writing URLConnections & CGI HELPPPPP!
                                  SunForumsGuest7-MOS
                                  Error 405 means that your web server does not allow you to send "POST" http requests to the Poster.pl file
                                  this is basicaly a very unusual restriction made by web server software.

                                  Where is this Poster.pl is hosted is it in a web server running in your PC or in somewhere else
                                  and what is the web server software.

                                  Make sure you have done following

                                  Poster.pl should be in your web sites cgi-bin folder or in a subfolder of the cgi-bin
                                  It should have permission 755

                                  The folder that your scrip saving the file should have permission 777 or the script must run with the userid

                                  make sure you give the excact url of the script in the constructor of URL object followed by a "?" mark.

                                  ex :- URL u = new URL("http://localhost/cgi-bin/Poster.pl")

                                  you must have PERL installed in the server computer which host Poster.pl and the web server must be configured for that
                                  • 14. Re: Writing URLConnections & CGI HELPPPPP!
                                    798701
                                    Wouldn't it be easier to use PHP, if you have it installed and configured?

                                    You can write to a file with the fwrite function. There documentation at php.net has a complete example.
                                    http://www.php.net/manual/function.fwrite.php
                                    1 2 Previous Next