HttpClient

By: aathishankaran Viewed: 177 times  Printer Friendly Format    


HttpClient

             The HttpClient class does the real network communication. It simply sends the designated request line and request headers to the Web server, then reads the lines that come back one at a time, placing them into a TextArea until either the server closes the connection or the HttpClient is interrupted by means of the isInterrupted flag.

String portString = portField.getTextField().getText();

if (portString.length() == 0) {

report("Missing port number");

return(false);

}

try {

port = Integer.parseInt(portString);

} catch(NumberFormatException nfe) {

report("Illegal port number: " + portString);

return(false);

}

requestLine =

requestLineField.getTextField().getText();

if (requestLine.length() == 0) {

report("Missing request line");

return(false);

}

getRequestHeaders();

return(true);

}

private void report(String s) {

resultArea.setText(s);

}

private void getRequestHeaders() {

for(int i=0; i<requestHeaders.length; i++)

requestHeaders[i] = null;

int headerNum = 0;

String header =

requestHeadersArea.getText();

StringTokenizer tok =

new StringTokenizer(header, "\r\n");

while (tok.hasMoreTokens())

requestHeaders[headerNum++] = tok.nextToken();

}

}

 

HttpClient.java

import java.awt.*;

import java.net.*;

import java.io.*;

 

public class HttpClient extends NetworkClient {

private String requestLine;

private String[] requestHeaders;

private TextArea outputArea;

private Interruptible app;

public HttpClient(String host, int port,

String requestLine, String[] requestHeaders,

TextArea outputArea, Interruptible app) {

super(host, port);

this.requestLine = requestLine;

this.requestHeaders = requestHeaders;

this.outputArea = outputArea;

this.app = app;

if (checkHost(host))

connect();

}

protected void handleConnection(Socket uriSocket)

throws IOException {

try {

PrintWriter out = SocketUtil.getWriter(uriSocket);

BufferedReader in = SocketUtil.getReader(uriSocket);

outputArea.setText("");

out.println(requestLine);

for(int i=0; i<requestHeaders.length; i++) {

if (requestHeaders[i] == null)

break;

else

out.println(requestHeaders[i]);

}

out.println();

String line;

while ((line = in.readLine()) != null &&

!app.isInterrupted())

outputArea.append(line + "\n");

if (app.isInterrupted())

outputArea.append("---- Download Interrupted ----");

} catch(Exception e) {

outputArea.setText("Error: " + e);

}

}



Most Viewed Articles (in JSP )

Latest Articles (in JSP)

Comment on this tutorial