android实现网页源码查看
测试在电脑运行模拟器以及tomcat后,点击查看按钮将tomcat页面的源码显示到TextView中,处理了无法在主线程中请求网络的问题。(无法显示百度以及google的页面源码,响应码出现302,405)
首先为布局文件源码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.LookWebPageCodeActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入你需要查看源码的网址"/>
<Button
android:id="@+id/bt_look"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看"/>
<!-- 注意:ScrollView中只能放一个控件,如果有多个控件请使用布局将控件包裹起来 -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
界面布局:
具体实现源码:
public class LookWebPageCodeActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_address;
private Button bt_look;
private TextView tv_content;
private Handler handler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initEvent();
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String temp = (String) msg.obj;
tv_content.setText(temp);
}
};
}
/**
* 初始化控件
*/
private void init(){
et_address = findViewById(R.id.et_address);
et_address.setText("http://10.0.2.2:8080");
bt_look = findViewById(R.id.bt_look);
tv_content = findViewById(R.id.tv_content);
}
/**
* 事件监听
*/
private void initEvent(){
bt_look.setOnClickListener(this);
}
@Override
public void onClick(View v) {
final String path = et_address.getText().toString().trim();
new Thread(){
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//设置请求方法
urlConnection.setRequestMethod("POST");
//连接超时的时间
urlConnection.setConnectTimeout(10000);
//获取响应码
int code = urlConnection.getResponseCode();
LogUtils.LOGI("LookWebPageCodeActivity","code = " + code);
if (code == 200){
InputStream inputStream = urlConnection.getInputStream();
String content = Utils.getStringFromStream(inputStream);
LogUtils.LOGI("LookWebPageCodeActivity","content = " + content);
Message msg = new Message();
msg.obj = content;
handler.handleMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}