Socket/UrlConnection获取网页

package com.itcast.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;

/**
 * 
 * @author Dao
 */
public class TestSocket {

	public TestSocket() {
	}

	public static void main(String args[]) {
		// 你想获取代码的网站
		String strServer = "www.sina.com";
		// 起始页面,/为根页
		String strPage = "/";

		try {
			// 设置端口,通常http端口不就是80罗,你在地址栏上没输就是这个值
			int port = 80;
			// 用域名反向获得IP地址
			InetAddress addr = InetAddress.getByName(strServer);

			// 建立一个Socket
			Socket socket = new Socket(addr, port);

			// 发送命令,无非就是在Socket发送流的基础上加多一些握手信息,详情请了解HTTP协议
			BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream(), "UTF-8"));
			wr.write("GET " + strPage + " HTTP/1.0\r\n");
			wr.write("HOST:" + strServer + "\r\n");
			wr.write("Accept:*/*\r\n");
			wr.write("\r\n");
			wr.flush();

			// 接收Socket返回的结果,并打印出来
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
			}
			// wr.close();
			rd.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
package com.itcast.socket.Second;
import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.net.URLConnection;  
  
public class URLTest {  
  
    public static void main(String[] args) {  
        URL url;  
        URLConnection urlconn;  
        try {  
            url = new URL("http://www.google.com.hk");  
            urlconn = url.openConnection();  
            HttpURLConnection httpConnection = (HttpURLConnection) urlconn;  
            httpConnection.setConnectTimeout(1000000);  
            httpConnection.setReadTimeout(1000000);  
//          httpConnection.setRequestProperty("User-Agent", "new");  
//          httpConnection.setRequestMethod("POST");  
            InputStream in = httpConnection.getInputStream();  
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "Big5"));  
  
            String line = "";  
            while((line = br.readLine()) != null) {  
                System.out.println(line);  
            }  
            br.close();  
            in.close();  
        } catch(IOException e) {  
            e.printStackTrace();  
        }  
    }  
}  
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值