在访问html网页的时候,实际上服务器是把该html源文件给你了,而我们之所以看到页面是浏览器把那个文本给解析了,然后把解析结果显示给你,而浏览器最终接收到的只是文本而已
我们请求一个html网址,实际上服务器是以流的形式把该html源文件写给客户端
String path = "https://www.baidu.com/";
try {
URL url = new URL(path);
//获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//先建立连接,再获取响应码
if(conn.getResponseCode() == 200){
//拿到服务器返回的输入流,流里的数据就是html的源文件
InputStream is = conn.getInputStream();
//从流里把文本数据取出来
String text = Utils.getTextFrom(is);
}
} catch (Exception e) {
e.printStackTrace();
}
}
从流中读数据方法:
public class Utils {
//创建专门从流里读数据的方法
public static String getTextFrom(InputStream is){
byte[] b = new byte[1024];
int len = 0;
//创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
//把字节数组输出流里的数据转换成字节数组
String text = new String(bos.toByteArray());
return text;
} catch (IOException e) {
e.printStackTrace();
}
//try出问题了就什么都读不到
return null;
}
}
因为建立网络连接,读取数据的方法是不能在主线程中运行,因此需要建立子线程,Handler
Handler handler = new Handler(){
public void handleMessage(Message msg) {
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText((String) msg.obj);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
Thread t = new Thread(){
@Override
public void run() {
String path = "https://www.baidu.com/";
try {
URL url = new URL(path);
//获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//先建立连接,再获取响应码
if(conn.getResponseCode() == 200){
//拿到服务器返回的输入流,流里的数据就是html的源文件
InputStream is = conn.getInputStream();
//从流里把文本数据取出来
String text = Utils.getTextFrom(is);
//发送消息,让主线程刷新UI,显示源文件
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
当服务器与客户端码表不一致时就会出现乱码,客户端默认时是utf-8,因此需要改服务器的码表为utf-8