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();
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章