您的位置:首页 > 其它

文章标题

2017-03-27 20:41 190 查看
网络源码查看器

//这是工具类
public class Utils {
public static String getTextFromStream(InputStream is) {

byte[] b = new byte[1024];
int len = 0;

//创建字节数组输出流,读取输入流的文本数据,挺尸把数据写入到输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
//is.read(b)以什么单位进行读取
while ((len = is.read(b)) != -1) {
bos.write(b,0,len);
}
//把字节数组转换成字节数组
String text = new String(bos.toByteArray());
return text;

} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}


实现步骤

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
tv.setText((String)msg.obj);
}
};
public void click(View v){
new Thread(){

String text1;
@Override
public void run() {

try {
String path = "https://www.baidu.com";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(3000);
if (conn.getResponseCode()==200){
InputStream is = conn.getInputStream();
text1 = Utils.getTextFromStream(is);
Message msg = Message.obtain();
msg.obj = text1;
handler.sendMessage(msg);
}else{
Toast.makeText(MainActivity.this,"链接失败",Toast.LENGTH_LONG).show();
}

} catch (Excep
8241
tion e) {
e.printStackTrace();
}

};
}.start();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: