1、布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<EditText
android:id="@+id/url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入网址"
/>
<Button
android:id="@+id/send"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始提取"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</LinearLayout>
2、主要代码
package com.get.demo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends Activity {
EditText url;
Button send;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
url = (EditText) findViewById(R.id.url);
send = (Button) findViewById(R.id.send);
text = (TextView) findViewById(R.id.text);
//按钮点击事件
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//执行httpGet方法
httpGet();
}
});
}
private void httpGet() {
//开子线程网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
BufferedReader reader=null;
String urls=url.getText().toString();
try {
URL url=new URL(urls);
connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
InputStream in=connection.getInputStream();
reader = new BufferedReader( new InputStreamReader(in));
StringBuilder response =new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
connection.disconnect();
}
}
}
}).start();
}
//切换为主线程
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
text.setText(new String(response.getBytes(),"UTF-8"));
//把获取的网页数据赋值给变量response,并设置给TextView控件
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
}
3、效果图

效果图
需要项目源码的点击这里下载吧!
网友评论