获取网络数据的基本思想:
注意:请求网路需要添加权限
需要添加的权限为:
1:创建子线程
2:获取网络连接路径
a.将网络连接路径转化为URL格式
3:根据URL路径打开一个连接
4:设置连接
5:获取服务器返回的值
6:解析返回的值
7:将解析的数据给控件赋值
实例:网络请求图片
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
//handler更新控件
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//加载布局
setContentView(R.layout.activity_main);
//获取控件
imageView = (ImageView) findViewById(R.id.image);
}
//点击事件...获取网络上的一张图片
public void getPic(View view){
getPicture();
}
//加载图片的方法
private void getPicture() {
//开启线程
new Thread(){
@Override
public void run() {
//图片的字符串路径
String path = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503854327078&di=08bdf32f7a117deafd580ca006b80a67&imgtype=0&src=http%3A%2F%2Fnews.k618.cn%2Fpic%2Fdmyx%2F201505%2FW020150501335817970176.jpg";
try {
//1.将路径转为url
URL url = new URL(path);
//2.根据url路径打开一个连接...HttpURLConnection extends URLConnection继承关系,,,遵循http协议的链接对象
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.设置
urlConnection.setRequestMethod("GET");//设置请求的方式,,,默认是get
urlConnection.setConnectTimeout(5000);//设置连接超时
urlConnection.setReadTimeout(5000);//设置读取超时
//4.获取响应的状态码...判断
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200){//成功
//5.服务器上的资源以什么形式返回...一字节流的形式
InputStream inputStream = urlConnection.getInputStream();
//6.把返回的字节流转换为图片资源 ..bitmap
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//设置....使用handler发送到主线程
//imageView.setImageBitmap(bitmap);
Message message = Message.obtain();
message.what = 0;
message.obj = bitmap;
//发送handler跟新组件
handler.sendMessage(message);
}else {
//0..1不能继续在使用
Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}