星期日, 五月 22, 2005

最简单的Http Client

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Date;
import java.util.Vector;
import java.util.StringTokenizer;

public class HTTPHammer
{
/** input and output streams for mSocket */
protected DataInputStream mIn;
protected DataOutputStream mOut;
URL url ;
protected Socket mSocket;

protected void openSocket() throws IOException
{
int port = url.getPort();
mSocket = new Socket(url.getHost(),
(port >= 0) ? port : 80);
mIn = new DataInputStream(new BufferedInputStream(mSocket.getInputStream()));
mOut = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream()));
}

public static void main(String[] args) throws Exception
{

//URLConnection conn = new URLConnection(url);
HTTPHammer hammer= new HTTPHammer();
hammer.url = new URL("http://www.szonline.net");
hammer.openSocket();
String protocol="GET / HTTP/1.0\r\nHost: www.szonline.net\r\n\r\n";
hammer.mOut.write(protocol.getBytes());
hammer.mOut.write("\r\n".getBytes());
hammer.mOut.flush();
byte[] b=new byte[40960];
long length=0L;
long totalLength=0L;
while((length=hammer.mIn.read(b))!=-1)
{
totalLength+=length;
System.out.println(new String(b));
}
System.out.println("Length:"+totalLength);
hammer.mSocket.close();
}
}