socket访问HTTP/1.1服务器

通过socket访问web并打印才出web内容.下面的方法比较原始,通过最底层的API实现.笔者再通过commons-io来实现.
package test.common.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class IO {

	public static void main(String[] args) throws Exception {
		Socket s = new Socket("121.9.238.94", 80);
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
		bw.write("GET / HTTP/1.1");
		bw.newLine();
		bw.write("Host:121.9.238.94:80");
		bw.newLine();
		bw.write("Content-Type:text/html");
		bw.newLine();
		bw.newLine();
		bw.flush();
		BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String str = null;
		while ((str = br.readLine()) != null) {
			System.out.println(str);
		}
		bw.close();
		br.close();
		s.close();
	}
}


    引入commons-io,只需要以下3行代码,既可实现上述功能.
package test.common.io;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;

public class IO {

	public static void main(String[] args) throws IOException {
		URL url = new URL("http://www.163.com");
		File file = new File("c:\\163.html");
		FileUtils.copyURLToFile(url, file);
		System.out.println(FileUtils.readFileToString(file, "gbk"));
	}
}

你可能感兴趣的:(java,apache,Web,.net,socket)