URLConnection模拟浏览器发送Http请求

/**
	 * URLConnection是在没有浏览器的情况下,也可以向http服务器发出http请求。用于模拟浏览器功能。
	 * @author zfx
	 * @throws Exception
	 */
	@Test
	public void getDemo() throws Exception{
		//1:声明url的字符串
		String str =  "http://127.0.0.1:8080/zfx/test";
		//2:声明url这个对象,用于接收一个连接的字符串
		URL url = new URL(str);
		//3:获取连接
		URLConnection con =  url.openConnection();
		//4:将con转成HttpUrlConnection
		HttpURLConnection hcon = 
				(HttpURLConnection) con;
		//5:打开连接
		hcon.connect();
		//6:从服务器获取状态码
		int code = hcon.getResponseCode();
		System.err.println("code is:"+code);
		//7:判断是否是200,如果是200则就从服务器上读取信息
		if(code==200){
			//8:从服务器获取io,读取从服务器返回的html文本
			InputStream in = hcon.getInputStream();
			byte[] b = new byte[1024];
			int len = 0;
			while((len=in.read(b))!=-1){
				String s = new String(b,0,len);
				System.err.println(s);
			}
		}
		//9:关闭连接
		hcon.disconnect();
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值