DataInputStream readLine()

public static String getHtml(String url){
		try{
			Socket clientSocket = new Socket(url, 80);
			clientSocket.setSoTimeout(20000);
			DataOutputStream outbound = new DataOutputStream(clientSocket.getOutputStream());
			DataInputStream inbound = new DataInputStream(clientSocket.getInputStream());
			outbound.writeBytes("GET / HTTP/1.1\r\nAccept:*/*\r\nUser-Agent: java/socket\r\nHost: www.biti.com\r\n\r\n");

                        /*inbound.readLine()*/
			String responseLine;
			BufferedReader bf = new BufferedReader(new InputStreamReader(inbound));

			while ((responseLine = bf.readLine()) != null){
				System.out.println(responseLine);
				if ( responseLine.indexOf("</HTML>") != -1 || responseLine.indexOf("</html>") != -1)
                    break;
			}
			outbound.close();
            inbound.close();
            clientSocket.close();
		}catch (IOException ioe){
			System.out.println("IOException: " + ioe);
			ioe.printStackTrace();
		}
		return "su";
	}


DataInputStream类的readLine()方法已经被弃用了,可以用上面的方法代替:
/*inbound.readLine()*/
			String responseLine;
			BufferedReader bf = new BufferedReader(new InputStreamReader(inbound));

使用bf.readLine();

对比下面这种方式的page fetch,哪一种好呢?

StringBuilder result = new StringBuilder();
	    try {
	    	URL URL = new URL(url);
	    	URLConnection conn = URL.openConnection();
	    	conn.setConnectTimeout(TIMEOUT);
	    	DataInputStream in = new DataInputStream(conn.getInputStream()) ;
	    	BufferedReader d = new BufferedReader(new InputStreamReader(in));
	    	while(d.ready()){
	    		result.append(d.readLine());
	    	}
	    }catch ( IOException ex ) {
	    	ex.printStackTrace();
	    }
	    return result.toString();

你可能感兴趣的:(java,socket)