...

View Full Version : GET and display a HTML file



twomt
01-22-2008, 07:59 AM
Hi all,

I am still learning Java and I am a bit stuck trying to open up a http connection to a webserver and then display the contents of a file.
I used the code found in a book, but I think something is missing on my server as I get a 400 returned from the server.

Have a look at the code please to see if I do something wrong and let me know if you have any ideas what I need to allow on the webserver to get the result I want:


/* Listing4504.java */

import java.net.*;
import java.io.*;

public class Listing4504
{
public static void main(String[] args)
{
if (args.length != 2) {
System.err.println(
"Usage: java Listing4504 <host> <file>"
);
System.exit(1);
}
try {
Socket sock = new Socket(args[0], 80);
OutputStream out = sock.getOutputStream();
InputStream in = sock.getInputStream();
//GET-command sending
String s = "GET " + args[1] + " HTTP/1.0" + "\r\n\r\n";
out.write(s.getBytes());
//Response read and display
int len;
byte[] b = new byte[100];
while ((len = in.read(b)) != -1) {
System.out.write(b, 0, len);
}
//Program exit
in.close();
out.close();
sock.close();
} catch (IOException e) {
System.err.println(e.toString());
System.exit(1);
}
}
}


Many thanks,
twomt

shyam
01-22-2008, 11:13 AM
check this http://www.exampledepot.com/egs/java.net/ReadFromURL.html

twomt
01-22-2008, 12:34 PM
Thanks for that, my code now looks as follows and I get the page returned to me and shown in a single line. Good enough for me, I can now start working on formatting the results received back.

If you have some hints and tips for that as well then I would highly appreciate your feedback.

To give you and idea of what am trying to achieve... I have written an online game in PHP and want now to create a client version for it to reduce the download times and so on (locally stored images, etc). The actual code remains on the server and so the client should just display what the server returns to him.

Thanks,
twomt.


/* Listing4504.java */

import java.net.*;
import java.io.*;

public class Listing4504
{
public static void main(String[] args)
{
try {
// Create a URL for the desired page
URL url = new URL("http://www.nemesiswar.net:80/client/index.html");

// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
System.out.print(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
System.err.println(e.toString());
System.exit(1);
}
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum