📄 httpclient.java
字号:
import java.io.*;
import java.net.*;
/**
* Class <em>HttpClient</em> is a class representing a simple
* HTTP client.
*
* @author iCarnegie, Inc (CTE)
* @version 1.0
*/
public class HttpClient
{
/**
* default HTTP port is port 8000
*/
private static int port = 8000;
/**
* Allow a maximum buffer size of 192 bytes
*/
private static int buffer_size = 8192;
/**
* Response is stored in a byte array.
*/
private byte[] buffer;
/**
* My socket to the world.
*/
Socket socket = null;
/**
* Default port is 8000.
*/
private static final int PORT = 8000;
/**
* Output stream to the socket.
*/
BufferedOutputStream ostream = null;
/**
* Input stream from the socket.
*/
BufferedInputStream istream = null;
/**
* StringBuffer storing the header
*/
private StringBuffer header = null;
/**
* StringBuffer storing the response.
*/
private StringBuffer response = null;
/**
* HttpClient constructor;
*/
public HttpClient() {
buffer = new byte[buffer_size];
header = new StringBuffer();
response = new StringBuffer();
}
/**
* <em>connect</em> connects to the input host on the default http port --
* port 80. This function opens the socket and creates the
* input and output streams used for communication.
*/
public void connect( String host ) throws Exception {
/**
* Open my socket to the specified host at
* the default port.
*/
socket = new Socket(host, PORT);
/**
* Create the output stream.
*/
ostream = new BufferedOutputStream(socket.getOutputStream());
/**
* Create the input stream.
*/
istream = new BufferedInputStream(socket.getInputStream());
}
/**
* <em>processGetRequest</em> process the input GET request.
*/
public void processGetRequest( String request ) throws Exception {
int last,c;
/**
* Send the request to the server.
*/
buffer = request.getBytes();
ostream.write(buffer, 0, request.length());
ostream.flush();
/**
* Process the header and add it to the header
* StringBuffer.
*/
last = 0;
boolean inHeader = true; // loop control
c = 0;
while(inHeader && ((c = istream.read()) != -1)) {
switch (c) {
case '\r':
break;
case '\n':
if (c == last) {
inHeader = false;
break;
}
last = c;
header.append("\n");
break;
default:
last = c;
header.append((char) c);
}
}
/**
* Read the contents and add it to the response StringBuffer.
*/
while(istream.read(buffer) != -1) {
response.append( new String(buffer) );
}
}
/**
* Get the response header.
*/
public String getHeader() {
return header.toString();
}
/**
* Get the server's response.
*/
public String getResponse() {
return response.toString();
}
/**
* Close all open connections -- sockets and streams.
*/
public void close() throws Exception {
socket.close();
istream.close();
ostream.close();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -