使用URL包而不是原始套接字检索网页
import java.io.*; import java.net.*; public class URLClient { /* 来 自* 时 代 Java 公 众 号 - nowjava.com */ public static void main(String argv[]) throws Exception { URL u = new URL("http://nowjava.com"); HttpURLConnection uC; int responseCode; InputStream input; BufferedReader remote; try { uC = (HttpURLConnection) u.openConnection(); System.out.println("port " + u.getPort()); responseCode = uC.getResponseCode(); } catch (Exception ex) { throw new Exception("first : " + ex.getMessage()); } /* 时 代 J a v a - nowjava.com 提 供 */ if (responseCode != HttpURLConnection.HTTP_OK) { throw new Exception("HTTP response code : " + String.valueOf(responseCode)); } try { input = uC.getInputStream(); remote = new BufferedReader(new InputStreamReader(input)); String line = new String(); // we will read and print a few lines only line = remote.readLine(); System.out.println(line); line = remote.readLine(); System.out.println(line); line = remote.readLine(); System.out.println(line); } catch (Exception ex) { throw new Exception(ex.getMessage()); } System.out.println(" host : " + u.getHost()); System.out.println(" protocol : " + u.getProtocol()); System.out.println(" port : " + u.getPort()); System.out.println