Android热身:通过网络获取资源并更新UI组件

时间:2021-05-01 21:10:18

Android热身:通过网络获取资源并更新UI组件

目标

点击“发送请求”按钮,下载某网页的html源码,并显示在TextView控件上;点击“清空”,清除TextView控件上的内容

效果图:

Android热身:通过网络获取资源并更新UI组件

Android热身:通过网络获取资源并更新UI组件

要点

开启网络权限

网络请求独立为一个模块

按钮点击事件的监听器

新开线程进行网络请求调用

用handler更新UI组件

源码

//MainActivity.java 主程序
package com.example.chris.handlerdemo; import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity implements Button.OnClickListener { private TextView statusTextView;
private Button btnDownload;
private Button btnClean; //uiHandler在主线程中创建,所以自动绑定主线程
private Handler uiHandler = new Handler(); @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
statusTextView = (TextView)findViewById(R.id.statusTextView);
btnDownload = (Button)findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(this); btnClean = (Button)findViewById(R.id.btnClean);
btnClean.setOnClickListener(this);
} @Override
public void onClick(View v){
if(v==btnDownload){
Thread downloadThread = new RockThread();
downloadThread.start();
}
else if(v==btnClean){
Thread cleanThread = new CleanThread();
cleanThread.start();
}
} class CleanThread extends Thread{
@Override
public void run() {
//btnClean.setText("");
Runnable runnable = new Runnable(){
@Override
public void run(){
statusTextView.setText("");
}
};
uiHandler.post(runnable);
}
} class RockThread extends Thread{
@Override
public void run(){
String url = "http://218.244.143.208/index.html";
final String response = NetUtils.get(url);
uiHandler.post(new Runnable() {
@Override
public void run() {
statusTextView.setText(response);
}
});
}
}
}
//NetUtils.java 网络请求模块
package com.example.chris.handlerdemo; import android.accounts.NetworkErrorException; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; /**
* Created by chris on 2016/5/12.
*/ public class NetUtils {
public static String post(String url, String content) {
HttpURLConnection conn = null;
try {
// 创建一个URL对象
URL mURL = new URL(url);
// 调用URL的openConnection()方法,获取HttpURLConnection对象
conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("POST");// 设置请求方法为post
conn.setReadTimeout(5000);// 设置读取超时为5秒
conn.setConnectTimeout(10000);// 设置连接网络超时为10秒
conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容 // post请求的参数
String data = content;
// 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容
OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据
out.write(data.getBytes());
out.flush();
out.close(); int responseCode = conn.getResponseCode();// 调用此方法就不必再使用conn.connect()方法
if (responseCode == 200) { InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
return response;
} else {
throw new NetworkErrorException("response status is "+responseCode);
} } catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();// 关闭连接
}
} return null;
} public static String get(String url) {
HttpURLConnection conn = null;
try {
// 利用string url构建URL对象
URL mURL = new URL(url);
conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode();
if (responseCode == 200) { InputStream is = conn.getInputStream();
String response = getStringFromInputStream(is);
return response;
} else {
throw new NetworkErrorException("response status is "+responseCode);
} } catch (Exception e) {
e.printStackTrace();
} finally { if (conn != null) {
conn.disconnect();
}
} return null;
} private static String getStringFromInputStream(InputStream is)
throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 模板代码 必须熟练
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码)
os.close();
return state;
}
}
//asynctask_activity.xml 布局文件
<?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" > <Button
android:id="@+id/btnDown"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="下载图片" /> <ImageView
android:id="@+id/ivSinaImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/> </LinearLayout>