packagecom.tsh.hrmlviewer;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;importcom.tsh.hrmlviewer.utils.StreamTools;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.text.TextUtils;importandroid.view.View;importandroid.widget.EditText;importandroid.widget.TextView;importandroid.widget.Toast;public class MainActivity extendsActivity {protected static final int SUCCESS = 1;protected static final int ERROR = 2;privateEditText et_path;privateTextView tv_show;//消息处理器
public Handler handler = newHandler() {public voidhandleMessage(Message msg) {switch(msg.what) {caseSUCCESS:
String text=(String) msg.obj;
tv_show.setText(text);break;caseERROR:
Toast.makeText(MainActivity.this, "获取数据失败", 0).show();break;
}
};
};
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path=(EditText) findViewById(R.id.et_path);
tv_show=(TextView) findViewById(R.id.tv_show);
}//查看
public voidclick(View v) {final String path =et_path.getText().toString().trim();if(TextUtils.isEmpty(path)) {
Toast.makeText(this, "请输入网址", 0).show();
}else{//开启新线程
newThread() {public voidrun() {try{
URL url= newURL(path);
HttpURLConnection conn=(HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);int code =conn.getResponseCode();if (code == 200) {
InputStream is=conn.getInputStream();
String res=StreamTools.readInputStream(is);
Message msg= newMessage();
msg.what=SUCCESS;
msg.obj=res;
handler.sendMessage(msg);
}else{
Message msg= newMessage();
msg.what=ERROR;
handler.sendMessage(msg);
}
}catch(Exception e) {
e.printStackTrace();
Message msg= newMessage();
msg.what=ERROR;
handler.sendMessage(msg);
}
}
}.start();
}
}
}