Android- 网络编程

1.网页源码查看器
   代码实现步骤
   [1]搭建UI
   
     [2]httpurlconnection类基本用法
 
 
  1. public void click(View view) {
  2. try {
  3. //1.获取用户输入的路径
  4. String path = et_path.getText().toString().trim();
  5. //2.访问这个路径
  6. URL url = new URL(path);
  7. //3.通过url对象获取httpurlconnection实例 该实例用于发送或者接收数据
  8. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  9. //4.设置一下联网超时时间
  10. conn.setConnectTimeout(5000);
  11. //5.设置一下请求的方式
  12. conn.setRequestMethod("GET"); //默认是get请求
  13. //6.获取服务器返回状态码
  14. int code = conn.getResponseCode();
  15. //7.对code做判断
  16. if (code == 200){
  17. //8.获取服务器返回的数据
  18. InputStream is = conn.getInputStream();
  19. //9.把流的数据读取出来 展示到textview上 由于把is转换为String是一个非常常见的操作 所以我们可以做一个工具类.
  20. String content = StreamUtils.readStream(is);
  21. //10.展示数据
  22. tv_content.setText(content);
  23. }
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. }
   [3]把流转换为String工具类
 
 
  1. public class StreamUtils {
  2. public static String readStream(InputStream is) throws Exception{
  3. //1.创建内存输出流
  4. ByteArrayOutputStream baso = new ByteArrayOutputStream();
  5. int len = 0;
  6. byte[] buf = new byte[1024];
  7. while((len = is.read(buf))!=-1){
  8. baso.write(buf,0,len);
  9. }
  10. //2.关流
  11. is.close();
  12. //baso 关闭此流无效
  13. return baso.toString();
  14. }
  15. }
 [4]联网要加上联网权限 
 
 
  1. <uses-permission android:name="android.permission.INTERNET"></uses-permission>
当加上权限后 也会报如下错误
 
 
  1. android.os.NetworkOnMainThreadException 主线程(UI线程)访问网络的异常. 主线程这个概念是谷歌提出的.
 为什么会报这个异常.谷歌要求 在主线程不能进行耗时(拷贝数据 连接网络)的操作,如果在主线程中进行耗时操作会报anr(应用无响应)异常; 如何解决?我们可以自己创建一个线程 来访问网络.
  [5]当我们把访问访问的操作放到子线程又会报如下错误:
 
 
  1. android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
  2. 只有主线程(UI线程)才可以更新UI
 [6].handler(助手)的使用  ---->负责线程的切换 
 6.1创建handler对象
 
 
  1. private Handler handler = new Handler(){
  2. //处理消息
  3. @Override
  4. public void handleMessage(Message msg) {
  5. //1.先获取消息携带的数据 数据是怎么携带的就怎么取
  6. String content = (String) msg.obj;
  7. //2在这个方法里面更新UI
  8. tv_content.setText(content);
  9. }
  10. };
 6.2 发消息
 
 
  1. //9.1构造message对象
  2. Message msg = new Message();
  3. //9.2 通过msg对象携带数据
  4. msg.obj = content;
  5. //10.使用handler进行线程的切换
  6. handler.sendMessage(msg); ///---->handleMessage方法就会执行 这样就从子线程切换到了主线程
7.scrollView  垂直滚动的view
 
 
  1. <ScrollView
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content">
  4. <TextView
  5. android:id="@+id/tv_content"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:text="Hello World!" />
  9. </ScrollView>
 注意:scrollView控件只能包裹一个孩子.如果想包裹多个在外面套一个布局.

2.handler原理
      
3.图片查看器
    [3.1]和源码查看器区别:1 UI不一样 
                                   2 数据展示的方式不一样
                                   3  访问路径的不一样 
    [3.2] runOnUIthread
 
 
  1. runOnUiThread(new Runnable() { //这个方法如果是在ui线程调用 那么这个方法会立即执行 如果调用这个方法不是在UI线程 那么要执行的动作也会运行到Ui线程
  2. @Override
  3. public void run() {
  4. //run方法里面执行逻辑 运行在主线程
  5. Toast.makeText(MainActivity.this, "服务器忙", Toast.LENGTH_SHORT).show();
  6. }
  7. });
    [3.3]bitmapFactory  位图工厂 
 
 
  1. final Bitmap bitmap = BitmapFactory.decodeStream(is);
4.综合案例  
   案例设计到知识点:listview --->baseAdapter  tomcat  xml(xml解析)     url  httpurlconnection 开线程 handler
   案例开发的流程
              开发这样一个程序 最少3个人  一个android客户端,一个UI设计师,做服务器开发人员.  产品经理(微信).
   代码实现过程:
   1.画UI
 
 
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="100dp">
  5. <com.loopj.android.image.SmartImageView
  6. android:id="@+id/iv_icon"
  7. android:layout_width="wrap_content"
  8. android:src="@mipmap/ic_launcher"
  9. android:layout_height="wrap_content"></com.loopj.android.image.SmartImageView>
  10. <TextView
  11. android:id="@+id/tv_title"
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:text="今日头条"
  15. android:textSize="22sp"
  16. android:textColor="#000000"
  17. android:layout_marginLeft="5dp"
  18. android:layout_marginTop="5dp"
  19. android:layout_toRightOf="@id/iv_icon"
  20. />
  21. <TextView
  22. android:id="@+id/tv_desc"
  23. android:layout_width="match_parent"
  24. android:layout_height="wrap_content"
  25. android:text="今日头条老师老师过来过时了阿拉嘎嘎嘎"
  26. android:textSize="17sp"
  27. android:textColor="#999999"
  28. android:layout_marginLeft="5dp"
  29. android:layout_marginTop="5dp"
  30. android:layout_toRightOf="@id/iv_icon"
  31. android:layout_below="@id/tv_title"
  32. />
  33. <TextView
  34. android:id="@+id/tv_type"
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:text="跟帖"
  38. android:textSize="20sp"
  39. android:textColor="#ff0000"
  40. android:layout_alignParentRight="true"
  41. android:layout_alignParentBottom="true"
  42. />
  43. </RelativeLayout>
2.搭建服务器 去服务器取数据
 
 
  1. private void initData() {
  2. new Thread() {
  3. @Override
  4. public void run() {
  5. try {
  6. //1.定义访问的路径
  7. String path = "http://192.168.126.62:8080/news/news.xml";
  8. //2.访问这个路径
  9. URL url = new URL(path);
  10. //3.通过url对象获取httpurlconnection实例 该实例用于发送或者接收数据
  11. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  12. //4.设置一下联网超时时间
  13. conn.setConnectTimeout(5000);
  14. //5.设置一下请求的方式
  15. conn.setRequestMethod("GET"); //默认是get请求
  16. //6.获取服务器返回状态码
  17. int code = conn.getResponseCode();
  18. //7.对code做判断
  19. if (code == 200) {
  20. //8.获取服务器返回的数据
  21. InputStream is = conn.getInputStream();
  22. //9.把流的数据读取出来 解析xml 把xml解析的数据封装到list<bean>
  23. lists = NewsXmlUtils.parserXml(is);
  24. //10.把集合里面的数据 通过适配器展示出来
  25. runOnUiThread(new Runnable() {
  26. @Override
  27. public void run() {
  28. //11.更新适配器
  29. lv.setAdapter(new MyAdaper());
  30. }
  31. });
  32. }
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. }
  37. }.start();
  38. }
3.对数据进行解析  xml解析
 
 
  1. public static List<News> parserXml(InputStream is) {
  2. List<News> lists=null;
  3. News news = null;
  4. // [1]获取解析器 xmlpullparser
  5. XmlPullParser parser = Xml.newPullParser();
  6. // [2]设置解析器要解析的内容
  7. try {
  8. parser.setInput(is, "utf-8");
  9. // [3]获取解析器的事件类型
  10. int eventType = parser.getEventType();
  11. // [4]不到文件结尾就一直解析
  12. while (eventType != XmlPullParser.END_DOCUMENT) {
  13. // [5]具体判断一下解析到的标签 然后把我们关系的数据取出来 封装到集合中
  14. switch (eventType) {
  15. case XmlPullParser.START_TAG: //代表解析到的所有开始的标签
  16. //[6]具体判断一下解析到的是哪个开始标签
  17. if ("channel".equals(parser.getName())) {
  18. //[7]创建一个集合对象
  19. lists =new ArrayList<News>();
  20. }else if ("item".equals(parser.getName())) {
  21. //[8]创建javabean对象
  22. news = new News();
  23. }else if ("title".equals(parser.getName())) {
  24. //[8.1]获取文本的数据
  25. news.setTitle(parser.nextText());
  26. }else if ("description".equals(parser.getName())) {
  27. //[8.1]获取文本的数据
  28. news.setDescription(parser.nextText());
  29. }else if ("image".equals(parser.getName())) {
  30. //[8.1]获取文本的数据
  31. news.setImagepath(parser.nextText());
  32. }else if ("type".equals(parser.getName())) {
  33. //[8.1]获取文本的数据
  34. news.setType(parser.nextText());
  35. }else if ("comment".equals(parser.getName())) {
  36. //[8.1]获取文本的数据
  37. news.setComment(parser.nextText());
  38. }
  39. break;
  40. case XmlPullParser.END_TAG: //解析到的所有的结束标签
  41. if("item".equals(parser.getName())){
  42. //把bean对象加入到集合中
  43. lists.add(news);
  44. }
  45. break;
  46. }
  47. // 不停解析
  48. eventType = parser.next();
  49. }
  50. //最后把集合对象返回
  51. return lists;
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. return null;
  55. }
  56. }
4.定义数据适配器 
 
 
  1. class MyAdaper extends BaseAdapter{
  2. @Override
  3. public int getCount() {
  4. return lists.size();
  5. }
  6. @Override
  7. public Object getItem(int position) {
  8. return null;
  9. }
  10. @Override
  11. public long getItemId(int position) {
  12. return 0;
  13. }
  14. //获取一个view 用来展示是每个条目的内容
  15. @Override
  16. public View getView(int position, View convertView, ViewGroup parent) {
  17. //1.优化
  18. View view;
  19. if (convertView == null){
  20. view = View.inflate(getApplicationContext(),R.layout.item,null);
  21. }else{
  22. view = convertView;
  23. }
  24. //2.找的条目控件
  25. TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
  26. TextView tv_desc = (TextView) view.findViewById(R.id.tv_desc);
  27. TextView tv_type = (TextView) view.findViewById(R.id.tv_type);
  28. SmartImageView siv = (SmartImageView) view.findViewById(R.id.iv_icon);
  29. //3.更新UI的数据
  30. News news = lists.get(position);
  31. tv_title.setText(news.getTitle()); //更新标题
  32. tv_desc.setText(news.getDescription()); //更新标题描述
  33. //4更新新闻类型
  34. String typee = news.getType();
  35. int type = Integer.parseInt(typee);
  36. switch (type){
  37. case 1:
  38. tv_type.setText("国内");
  39. break;
  40. case 2:
  41. tv_type.setText("娱乐");
  42. break;
  43. case 3:
  44. tv_type.setText("体育");
  45. break;
  46. }
  47. //5.展示图片信息
  48. String imagepath = news.getImagepath();
  49. siv.setImageUrl(imagepath);
  50. return view;
  51. }
  52. }
5.smartImageview
   5.1要先声明 要求这个类的完整包名和类名
 
 
  1. <com.loopj.android.image.SmartImageView
  2. android:id="@+id/iv_icon"
  3. android:layout_width="wrap_content"
  4. android:src="@mipmap/ic_launcher"
  5. android:layout_height="wrap_content"></com.loopj.android.image.SmartImageView>
  5.2找的控件 展示数据
 
 
  1. //5.展示图片信息
  2. String imagepath = news.getImagepath();
  3. siv.setImageUrl(imagepath);

   

 
    
   
       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值