Class 2 | Intermediate Java 30-IT-397 |
Connecting to HTTP
/*
* SocketResponse.java
*
* Created on April 29, 2002, 9:21 PM
*/
// Import the JOptionPane, io and net packages.
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
/**
*
* @author default
*/
public class SocketResponse {
/** Creates a new instance of SocketResponse
*/
public SocketResponse() {
}
/**
* Prompt the user for host and port.
* Create a connection and return the results.
*
*/
public void connect() {
// Prompt the user for
information.
String host = JOptionPane.showInputDialog("Please
enter the host to which you wish to connect.");
String port = JOptionPane.showInputDialog("Please
enter the port.");
// try-catch block for
possible exceptions.
try {
// Create a socket.
Socket socket = new Socket(host, Integer.parseInt(port));
// Create a buffered reader and input stream to read the response.
// We can get the input stream from the socket, and we can pass that to
the buffered reader
// constructor.
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
boolean moreData = true;
// Read while we have information to read.
while(moreData) {
// Read a line from the buffered reader.
String line = in.readLine();
// Read the data, or let the loop know we're finished.
if (line == null) {
moreData = false;
} else {
System.out.println(line);
} // end if.
} // end for.
// Handle exceptions.
} catch (NumberFormatException
e) {
System.out.println("Enter the port as a number, please. Message:
" + e.getMessage());
e.printStackTrace();
} catch (IOException
e) {
System.out.println("IOException caught while attempting connection.
Message: " + e.getMessage());
e.printStackTrace();
}
} // end connect()
// The main method starts the program.
public static void main(String args[]) {
SocketResponse socketResponse
= new SocketResponse();
socketResponse.connect();
}
}
Created by: Brandan Jones December 17, 2001