日期:2014-05-20 浏览次数:20874 次
import java.io.*; import java.net.*; public class TestSocket { public static void main(String[] args) { String result = getResult("www.china.com", 80); System.out.println(result); } public static String getResult(String ip, int port) { Socket socket = null; BufferedReader bufferedReader = null; StringBuffer result = null; try { //建立连接 socket = new Socket(ip, port); bufferedReader = new BufferedReader(new InputStreamReader(socket .getInputStream(), "GBK")); //发出请求 OutputStream out = socket.getOutputStream(); StringBuffer stringBuffer = new StringBuffer( "GET /index.html HTTP/1.1\r\n"); stringBuffer.append("User-Agent: Java/1.6.0_20\r\n"); //Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR stringBuffer.append("Host: www.pconline.com.cn:80\r\n"); stringBuffer .append("Accept: text/html\r\n");//取html文本内容 stringBuffer.append("Connection: Close\r\n"); stringBuffer.append("\r\n"); out.write(stringBuffer.toString().getBytes()); //取得相应 result = new StringBuffer(); String tempString = null; while ((tempString = bufferedReader.readLine()) != null) { result.append(tempString); result.append("\r\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bufferedReader != null) bufferedReader.close(); if (socket != null) socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result.toString(); } }