Home arrow static arrow Java Programming [Archive] - Writing URLConnections & CGI HELPPPPP!
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Writing URLConnections & CGI HELPPPPP!
10 Duke Stars available
This topic has 16 replies on 2 pages.    1 | 2 | Next »

Posts:58
Registered: 7/6/04
Writing URLConnections & CGI HELPPPPP!  
Jul 6, 2004 9:42 PM



 
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");
}

}
}

 

Posts:951
Registered: 6/7/01
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 6, 2004 10:47 PM (reply 1 of 16)



 
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.
 

Posts:58
Registered: 7/6/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 6, 2004 11:57 PM (reply 2 of 16)



 
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
 

Posts:55
Registered: 6/12/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:17 AM (reply 3 of 16)



 

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.
 

Posts:11,200
Registered: 7/22/99
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:22 AM (reply 4 of 16)



 
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
 

Posts:58
Registered: 7/6/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:28 AM (reply 5 of 16)



 
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!
 

Posts:11,200
Registered: 7/22/99
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:47 AM (reply 6 of 16)



 
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.
 

Posts:55
Registered: 6/12/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:53 AM (reply 7 of 16)



 

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
 

Posts:951
Registered: 6/7/01
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 12:59 AM (reply 8 of 16)



 
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.
 

Posts:58
Registered: 7/6/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 1:16 AM (reply 9 of 16)



 
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"
?>
 

Posts:951
Registered: 6/7/01
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 1:53 AM (reply 10 of 16)



 
I have no idea how to do uploads in php. Maybe do a search?
 

Posts:2,002
Registered: 7/5/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 5:08 AM (reply 11 of 16)



 
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 modebinmode STDIN; #//  Reading the Data send by the clientread STDIN,$var,$ENV{'CONTENT_LENGTH'}; #// retriving the filename to save from the Query Stringmy $fileNameToSave = $ENV{'QUERY_STRING'}; #// Opening the file for writingopen(FILEHANDLE, ">$fileNameToSave"); #// Switching to the binary Datatransfer modebinmode FILEHANDLE; #// Writing Dataprint FILEHANDLE $var;#// Closing The Fileclose(FILEHANDLE); #// Sending a valid response to the client through the web serverprint "Cache-Control: no-cache\n";print "Content-Type: text/html\n\n"; print "<pre>\n";print "Got The File. Thankx\n";print "</pre>\n"
 

Posts:58
Registered: 7/6/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 4:03 PM (reply 12 of 16)



 
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.
 

Posts:2,002
Registered: 7/5/04
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 7, 2004 8:08 PM (reply 13 of 16)



 
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
 

Posts:11,200
Registered: 7/22/99
Re: Writing URLConnections & CGI HELPPPPP!  
Jul 8, 2004 12:46 AM (reply 14 of 16)



 
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
 
This topic has 16 replies on 2 pages.    1 | 2 | Next »