Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Http in java

  Asked By: Daryl    Date: Jul 16    Category: Java    Views: 607

does anyone know how to access web pages using java and mor
eimportantly get the file size



2 Answers Found

Answer #1    Answered By: Dominic Murphy     Answered On: Jul 16

Try using these two java  objects: java.net.URL and java.net.Socket
for the APIs see: http://java.sun.com/j2se/1.4.1/docs/api/

Here is an example from Java Examples in a Nutshell

* Copyright (c) 2000 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this
* For a commercial use license, or to purchase the book
* visit http://www.davidflanagan.com/javaexamples2.
import java.io.*;
import java.net.*;

* This program connects to a Web server and downloads the specified
* from it. It uses the http  protocol directly.
public class HttpClient {
public static void main(String[] args) {
try {
// Check the arguments
if ((args.length != 1) && (args.length != 2))
throw new IllegalArgumentException("Wrong number of

// Get an output stream to write the URL contents to
OutputStream to_file;
if (args.length == 2) to_file = new FileOutputStream(args
else to_file = System.out;

// Now use the URL class to parse the user-specified URL
// its various parts.
URL url = new URL(args[0]);
String protocol = url.getProtocol();
if (!protocol.equals("http")) // Check that we support
the protocol
throw new IllegalArgumentException("Must use 'http:'
String host = url.getHost();
int port = url.getPort();
if (port == -1) port = 80; // if no port, use the default
HTTP port
String filename = url.getFile();

System.out.println("filename "+filename);

// Open a network socket connection to the specified host
and port
Socket socket = new Socket(host, port);

// Get input and output streams for the socket
InputStream from_server = socket.getInputStream();
PrintWriter to_server = new PrintWriter

// Send the HTTP GET command to the Web server,
specifying the file
// This uses an old and very simple version of the HTTP
to_server.print("GET " + filename + "\n\n");
to_server.flush(); // Send it right now!

// Now read the server's response, and write it to the
byte[] buffer = new byte[4096];
int bytes_read;
while((bytes_read = from_server.read(buffer)) != -1)
to_file.write(buffer, 0, bytes_read);

// When the server closes the connection, we close our
catch (Exception e) { // Report any errors that arise
System.err.println("Usage: java HttpClient <URL>

Answer #2    Answered By: Jeffrey Washington     Answered On: Jul 16

I'm using the HTTPClient classes from ww.innovation.ch they even support
and cookies.

Didn't find what you were looking for? Find more on Http in java Or get search suggestion and latest updates.