一、布局:
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="@+id/get"
android:text="获取数据"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/get"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/text"
android:layout_below="@+id/get"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</ScrollView>
二、在主线程中
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String path;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
path = "http://www.baidu.com";
Button get = (Button) findViewById(R.id.get);
get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getHttpurlConnection();
handler = new Handler() {//更新主线程UI
@Override
public void handleMessage(Message msg) {
if(msg.what == 1) {
textView.setText(msg.obj.toString());
}
}
};
}
});
}
三、子线程中
private void getHttpurlConnection() {
new Thread(new Runnable() {//创建线程
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();//与百度首页链接
connection.setRequestMethod("GET");
connection.setConnectTimeout(200);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));获取百度首页源代码并封装成BufferedReader
String s1;
StringBuilder s =new StringBuilder();//使用StringBuilder可以拼接获取的字符
while ((s1 = br.readLine()) != null) {
Message msg = new Message();
msg.what = 1;
s.append(s1);
msg.obj=s;
handler.sendMessage(msg);//发送msg给主线程
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}