public Test(String host) throws UnknownHostException,IOException { this(host,80); }
public Test(String host,int port) throws UnknownHostException,IOException { sock = new Socket(host,port); inReader = new BufferedReader( new InputStreamReader(sock.getInputStream())); outWriter = new BufferedWriter( new OutputStreamWriter(sock.getOutputStream())); }
import java.net.*; public class suckURL {
String aFile;
String aURL; public static void main(String args[]) {
// GIF JAVA How-to at Real's Home
String url =
"http://www.rgagnon.com/images/";
suckURL b = new suckURL(url, "jht.gif");
b.doit();
} suckURL(String u, String s){
aURL = u;
aFile = s;
} public void doit() {
DataInputStream di = null;
FileOutputStream fo = null;
byte [] b = new byte[1];
try {
System.out.println("Sucking " + aFile);
System.out.println(" at " + aURL );
// input
URL url = new URL(aURL + aFile);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
di = new DataInputStream(urlConnection.getInputStream()); // output
fo = new FileOutputStream(aFile); // copy the actual file
// (it would better to use a buffer bigger than this)
while(-1 != di.read(b,0,1))
fo.write(b,0,1);
di.close();
fo.close();
}
catch (Exception ex) {
System.out.println("Oups!!!");
ex.printStackTrace();
System.exit(1);
}
System.out.println("done.");
}
}
仅共参考:
Sample:
import java.io.*;
import java.net.*;public class Test {
private Socket sock = null;
private BufferedReader inReader = null;
private BufferedWriter outWriter = null;
public Test(String host)
throws UnknownHostException,IOException {
this(host,80);
}
public Test(String host,int port)
throws UnknownHostException,IOException {
sock = new Socket(host,port);
inReader = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
outWriter = new BufferedWriter(
new OutputStreamWriter(sock.getOutputStream()));
}
public void bye() throws IOException {
inReader.close();
inReader = null;
outWriter.close();
outWriter = null;
sock.close();
sock = null;
}
public static void main(String[] args) {
try {
Test t = new Test("www.263.net");
t.outWriter.write("GET /user/register.html HTTP/1.0\r\n\r\n");
t.outWriter.flush();
String text = null;
while((text = t.inReader.readLine()) != null) {
System.out.println(text);
}
t.bye();
}
catch(UnknownHostException unKnownHostError) {
unKnownHostError.printStackTrace();
System.exit(0);
}
catch(IOException ioError) {
ioError.printStackTrace();
System.exit(0);
}
}
}