导语
网络编程介绍
一、网络图片查看器
1.1 主线程网络图片查看器
- 1 确定图片的网址 - //确定图片的网址 String address = "http://192.168.1.102:8080/dd.jpg";
- 2 发送http请求 - URL url = new URL(address); //获取连接对象,并没有建立连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置连接和读取超时 conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //设置请求方法,注意必须大写 conn.setRequestMethod("GET"); //建立连接,发送get请求 //conn.connect(); //建立连接,然后获取响应吗,200说明请求成功 conn.getResponseCode();
- 3 服务器的图片是以流的形式返回给浏览器的 - //拿到服务器返回的输入流 InputStream is = conn.getInputStream(); //把流里的数据读取出来,并构造成图片 Bitmap bm = BitmapFactory.decodeStream(is);
- 4 把图片设置为ImageView的显示内容,直接在主线程刷新UI页面 - ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap(bm);
- 5 添加权限
1.2 主线程不能被阻塞
- 在Android中,主线程被阻塞会导致应用不能刷新ui界面,不能响应用户操作,用户体验将非常差
- 主线程阻塞时间过长,系统会抛出ANR异常
- ANR:Application Not Response;应用无响应
- 任何耗时操作都不可以写在主线程
- 因为网络交互属于耗时操作,如果网速很慢,代码会阻塞,所以网络交互的代码不能运行在主线程
1.3只有主线程能刷新ui
- 刷新ui的代码只能运行在主线程,运行在子线程是没有任何效果的
- 如果需要在子线程中刷新ui,使用消息队列机制
- 主线程也叫ui线程
1.3.1消息队列
- 主线程创建时,系统会同时创建消息队列对象(MessageQueue)和消息轮询器对象(Looper)
- 轮询器的作用,就是不停的检测消息队列中是否有消息(Message)
- Looper一旦发现Message Queue中有消息,就会把消息取出,然后把消息扔给Handler对象,Handler会调用自己的handleMessage方法来处理这条消息
- handleMessage方法运行在主线程
- 主线程创建时,消息队列和轮询器对象就会被创建,但是消息处理器对象,需要使用时,自行创建 - //消息队列 Handler handler = new Handler(){ //主线程中有一个消息轮询器looper,不断检测消息队列中是否有新消息,如果发现有新消息,自动调用此方法,注意此方法是在主线程中运行的 public void handleMessage(android.os.Message msg) { } };
- 在子线程中使用Handler对象往消息队列里发消息 - //创建消息对象 Message msg = new Message(); //消息的obj属性可以赋值任何对象,通过这个属性可以携带数据 msg.obj = bm; //what属性相当于一个标签,用于区分出不同的消息,从而运行不能的代码 msg.what = 0; //发送消息 handler.sendMessage(msg);
- 通过switch语句区分不同的消息 - public void handleMessage(android.os.Message msg) { switch (msg.what) { //如果是1,说明属于请求成功的消息 case 0: ImageView iv = (ImageView) findViewById(R.id.iv); Bitmap bm = (Bitmap) msg.obj; iv.setImageBitmap(bm); break; case 1: Toast.makeText(MainActivity.this, "请求失败", 0).show(); break; } }
1.4 加入缓存图片的功能
- 把服务器返回的流里的数据读取出来,然后通过文件输入流写至本地文件 - //1.拿到服务器返回的输入流 InputStream is = conn.getInputStream(); //2.把流里的数据读取出来,并构造成图片 FileOutputStream fos = new FileOutputStream(file); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b)) != -1){ fos.write(b, 0, len); }
- 创建bitmap对象的代码改成 - Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
- 每次发送请求前检测一下在缓存中是否存在同名图片,如果存在,则读取缓存 - // 点击事件 public void click(View v) { // 图片的地址 final String address = "http://192.168.1.102:8080/dd.jpg"; // 封装图片的缓存文件 final File file = new File(getCacheDir(), _getFileName(address)); // 判断图片缓存文件是否存在 if (file.exists()) { // 图片缓存文件存在 Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath()); ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap(bm); } else { // 图片缓存文件不存在 Thread t = new Thread() { public void run() { } }; t.start(); } }
1.5 网络图片查看器示例
public class MainActivity extends Activity {
    // 主线程定义Handler
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 0:
                ImageView iv = (ImageView) findViewById(R.id.iv);
                iv.setImageBitmap((Bitmap) msg.obj);
                break;
            case 1:
                Toast.makeText(MainActivity.this, "请求失败", 0).show();
                break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // 点击事件
    public void click(View v) {
        // 图片的地址
        final String address = "http://192.168.1.102:8080/dd.jpg";
        // 封装图片的缓存文件
        final File file = new File(getCacheDir(), _getFileName(address));
        // 判断图片缓存文件是否存在
        if (file.exists()) {
            // 图片缓存文件存在
            Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
            ImageView iv = (ImageView) findViewById(R.id.iv);
            iv.setImageBitmap(bm);
        } else {
            // 图片缓存文件不存在
            Thread t = new Thread() {
                public void run() {
                    try {
                        // 1,2 将图片网址字符串地址封装成URL
                        URL url = new URL(address);
                        // 3 获取连接对象,此方法只是获取连接对象,方便操作参数,并不会发送请求
                        HttpURLConnection conn = (HttpURLConnection) url
                                .openConnection();
                        // 4 设置请求参数,注意大写
                        conn.setRequestMethod("GET");
                        // 连接超时
                        conn.setConnectTimeout(8000);
                        // 读取超时
                        conn.setReadTimeout(8000);
                        // 5 发送请求,建立连接(此步可不写,自动发送)
                        conn.connect();
                        // 6.获取响应码,进行判断
                        if (conn.getResponseCode() == 200) {
                            // 服务器响应正常
                            // 7.拿到服务器返回的流,流里的数据,就是客户端请求的内容
                            InputStream is = conn.getInputStream();
                            // 将流里的数据(一张图片)缓存到本地
                            FileOutputStream os = new FileOutputStream(file);
                            byte[] bt = new byte[1024];
                            int len;
                            while ((len = is.read(bt)) != -1) {
                                os.write(bt, 0, len);
                            }
                            os.close();
                            // 将本地的缓存文件数据读取出来,并构成图片
                            Bitmap bm = BitmapFactory.decodeFile(file
                                    .getAbsolutePath());
                            // 由于子线程不能刷新UI界面,将数据发送到主线程消息队列,让主线程刷新UI页面
                            // 发送消息到消息队列
                            // 获取消息对象,//如果消息池有空消息,使用消息池的消息,如果没有,此方法会自动创建一个消息对象
                            Message msg = handler.obtainMessage();
                            // 利用消息对象携带数据
                            msg.obj = bm;
                            msg.what = 0;
                            // 将消息发送到消息队列
                            handler.sendMessage(msg);
                        } else {
                            // 各种情况使得客户端请求失败,或服务器端响应失败
                            // 将失败消息发送到消息队列
                            handler.sendEmptyMessage(1);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
    }
    // 获取缓存文件夹下的文件名
    public String _getFileName(String address) {
        int index = address.lastIndexOf("/");
        return address.substring(index + 1);
    }
}
1.6 获取开源代码的网站
- code.google.com
- github.com
- 在github搜索smart-image-view
- 下载开源项目smart-image-view
- 使用自定义组件时,标签名字要写包名 - <com.loopj.android.image.SmartImageView/>
- SmartImageView的使用 - SmartImageView siv = (SmartImageView) findViewById(R.id.siv); siv.setImageUrl("http://192.168.1.102:8080/dd.jpg");
1.7 Html源文件查看器
- 1 发送GET请求 - URL url = new URL(path); //获取连接对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置连接属性 conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); //建立连接,获取响应吗 if(conn.getResponseCode() == 200){ //拿到服务器返回的流,流里的数据,就是客户端请求的内容 InputStream is = conn.getInputStream(); }
- 2 获取服务器返回的流,从流中把html源码读取出来 - byte[] b = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while((len = is.read(b)) != -1){ //把读到的字节先写入字节数组输出流中存起来 bos.write(b, 0, len); } //把字节数组输出流中的内容转换成字符串 //默认使用utf-8 text = new String(bos.toByteArray());
-Html源文件查看器示例————————-
public class MainActivity extends Activity {
//主线程定义消息处理器
Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
        case 0:
            TextView tv = (TextView) findViewById(R.id.tv);
            tv.setText((String)msg.obj);
            break;
        case 1:
            Toast.makeText(MainActivity.this, "请求失败啦啦啦么么哒", 0).show();
            break;
        }
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
//点击事件:查看html文件源码
public void click(View v){
    Thread t = new Thread(){
        @Override
        public void run() {
            String path = "http://192.168.15.27:8080/baidu.html";
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);
                //先发送请求,然后获取相应码
                if(conn.getResponseCode() == 200){
                    //拿到服务器返回的流,流里的数据,就是客户端请求的内容
                    InputStream is = conn.getInputStream();
                    //将输入流数据,转换为字符串
                    String text = Tools.getTextFromStream(is);
                    //发送消息到消息队列,触发主界面刷新页面
                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
                else{
                    handler.sendEmptyMessage(1);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    t.start();
}
}
1.8 乱码的处理
- 乱码的出现是因为服务器和客户端码表不一致导致 - //手动指定码表 text = new String(bos.toByteArray(), "gb2312");
- 在定义工具类时,将输入流数据转换为字符串,此时手动指定码表 - public class Tools { - public static String getTextFromStream(InputStream is){ byte[] b = new byte[1024]; int len; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { while((len = is.read(b)) != -1){ bos.write(b, 0, len); } String text = new String(bos.toByteArray()); return text; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }- } 
二、提交数据
2.1 GET方式提交数据
- get方式提交的数据是直接拼接在url的末尾 - final String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + name + "&pass=" + pass;
- 发送get请求,代码和之前一样 - URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); if(conn.getResponseCode() == 200){ }
- 浏览器在发送请求携带数据时会对数据进行URL编码,我们写代码时也需要为中文进行URL编码 - String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;
-GET方式提交数据示例———————————————
public class MainActivity extends Activity {
//主线程定义消息处理器Handler
Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
//点击事件,get提交用户名,密码
public void click(View v){
    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);
    String name = et_name.getText().toString();
    String pass = et_pass.getText().toString();
    @SuppressWarnings("deprecation")
        //客户端提交的表单数据都会被url编码
    final String path = "http://192.168.15.27/Web2/servlet/LoginServlet?name=" + URLEncoder.encode(name) + "&pass=" + pass;
    Thread t = new Thread(){
        @Override
        public void run() {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);
                if(conn.getResponseCode() == 200){
                    //服务器成功响应,拿到服务器返回的流
                    InputStream is = conn.getInputStream();
                    //将流中的数据转成字符串
                    String text = Tools.getTextFromStream(is);
                    // 发送消息到消息队列,在主线程刷新页面
                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    t.start();
}
}
//工具类
public class Tools {
    //读取输入流的数据,返回字符串
    public static String getTextFromStream(InputStream is){
        byte[] b = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            String text = new String(bos.toByteArray());
            return text;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}
2.2 POST方式提交数据
- post提交数据是用流写给服务器的
- 协议头中多了两个属性 - Content-Type: application/x-www-form-urlencoded,描述提交的数据的mimetype
- Content-Length: 32,描述提交的数据的长度 - //给请求头添加post多出来的两个属性 String data = "name=" + URLEncoder.encode(name) + "&pass=" + pass; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length() + "");
 
- 设置允许打开post请求的流 - conn.setDoOutput(true);
- 获取连接对象的输出流,往流里写要提交给服务器的数据 - OutputStream os = conn.getOutputStream(); os.write(data.getBytes());
-POST方式提交数据—————————-
public class MainActivity extends Activity {
    //主线程定义消息处理器Handler
    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    //点击事件,post提交用户名,密码
    public void click(View v){
        EditText et_name = (EditText) findViewById(R.id.et_name);
        EditText et_pass = (EditText) findViewById(R.id.et_pass);
        final String name = et_name.getText().toString();
        final String pass = et_pass.getText().toString();
        @SuppressWarnings("deprecation")
        final String path = "http://192.168.15.27/Web2/servlet/LoginServlet";
        Thread t = new Thread(){
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    //拼接去要提交的数据
                    String content = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
                    //添加post请求头中的属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", content.length() + "");
                    //设置开启客户端的输出流
                    conn.setDoOutput(true);
                    //获取客户端的输出流,客户端可以通过此流把数据传递给服务器
                    OutputStream os = conn.getOutputStream();
                    os.write(content.getBytes());
                    if(conn.getResponseCode() == 200){
                        InputStream is = conn.getInputStream();
                        String text = Tools.getTextFromStream(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}
案例综合:新闻客户端(解析xml,ListView)
public class MainActivity extends Activity {
    List
    // 主线程定义信息处理器Handler
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            // 获取ListView布局文件
            ListView lv = (ListView) findViewById(R.id.lv);
            // 为ListView设置适配器
            lv.setAdapter(new MyAdapter());
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 界面一打开,执行此方法
        getNewsInfo();
    }
    /**
 * 自定义一个复杂的BaseAdapter
 * 
 * @author Administrator
 */
class MyAdapter extends BaseAdapter {
    @Override
    public int getCount() {
        return newsList.size();
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        ViewHolder vholder = null;
        News news = newsList.get(position);
        if (convertView == null) {
            // 填充器将一个布局文件,转成view对象
            view = View.inflate(MainActivity.this, R.layout.item_listview,null);
            vholder = new ViewHolder();
            vholder.tv_title = (TextView) view.findViewById(R.id.tv_title);
            vholder.tv_detail = (TextView) view
                    .findViewById(R.id.tv_detail);
            vholder.tv_comment = (TextView) view
                    .findViewById(R.id.tv_comment);
            vholder.siv = (SmartImageView) view.findViewById(R.id.iv);
            // 将vholder封装到view对象中,vholder会和view一起缓存起来
            view.setTag(vholder);
        } else {
            view = convertView;
            vholder = (ViewHolder) view.getTag();
        }
        vholder.tv_title.setText(news.getTitle());
        vholder.tv_detail.setText(news.getDetail());
        vholder.tv_comment.setText(news.getComment() + "条评论");
        vholder.siv.setImageUrl(news.getImage());
        return view;
    }
    class ViewHolder {
        TextView tv_title;
        TextView tv_detail;
        TextView tv_comment;
        SmartImageView siv;
    }
}
/**
 * 请求查看服务器端xml文件
 */
private void getNewsInfo() {
    Thread t = new Thread(){
        public void run() {
            // 1查看xml文件的网址
            String address = "http://192.168.1.102:8080/news.xml";
            // 2封装字符串地址成URL
            URL url;
            try {
                url = new URL(address);
                // 3获取连接对象
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 4设置请求参数
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);
                // 5
                // 6获取响应码,进行判断
                if (conn.getResponseCode() == 200) {
                    // 拿到服务器返回的流,流里的数据,就是请求的内容
                    InputStream is = conn.getInputStream();
                    // 用pull解析xml
                    parseNewsXml(is);// (第二天讲的Android下,xml数据解析,登录演示中,
                                        // 实现读取之前保存在xml中的数据,并显示到控件上功能)
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}
/**
 * 解析xml数据,将数据存到news对象中,将news对象存放到newsList集合中
 * 
 * @param is
 */
private void parseNewsXml(InputStream is) {
    try {
        // 创建xml解析器
        XmlPullParser parser = Xml.newPullParser();
        // 初始化xml解析器,指定解析那个流,以什么编码格式解析
        parser.setInput(is, "UTF-8");
        // 解析xml数据
        int type = parser.getEventType();// xml标签节点类型
        News news = null;
        while (type != XmlPullParser.END_DOCUMENT) {// 循环结束的条件
            switch (type) {
            case XmlPullParser.START_TAG:
                if ("newslist".equals(parser.getName())) {
                    newsList = new ArrayList<News>();
                } else if ("news".equals(parser.getName())) {
                    news = new News();
                } else if ("title".equals(parser.getName())) {
                    String title = parser.nextText();
                    news.setTitle(title);
                } else if ("detail".equals(parser.getName())) {
                    String detail = parser.nextText();
                    news.setDetail(detail);
                } else if ("comment".equals(parser.getName())) {
                    String comment = parser.nextText();
                    news.setComment(comment);
                } else if ("image".equals(parser.getName())) {
                    String image = parser.nextText();
                    news.setImage(image);
                }
                break;
            case XmlPullParser.END_TAG:
                if ("news".equals(parser.getName())) {
                    newsList.add(news);
                }
                break;
            }
            type = parser.next();
        }
        // 发送一个消息到消息队列,触发handleMessage()方法
        handler.sendEmptyMessage(0);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}