/**
* 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();
}
URLConnection模拟浏览器发送Http请求
最新推荐文章于 2022-08-08 20:37:52 发布