您的位置:首页 > 理论基础 > 计算机网络

Android应用开发-网络编程(一)

2016-06-18 16:09 531 查看

网络图片查看器

  1. 确定图片的网址

  2. 发送http请求

URL url = new URL(address);
// 获取客户端和服务器的连接对象,此时还没有建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式,注意必须大写
conn.setRequestMethod("GET");
// 设置连接和读取超时
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 发送请求,与服务器建立连接
conn.connect();
// 如果响应码为200,说明请求成功
if(conn.getResponseCode() == 200){

}


  3. 服务器的图片是以流的形式返回给浏览器的

InputStream is = conn.getInputStream();   // 拿到服务器返回的输入流
Bitmap bm = BitmapFactory.decodeStream(is);// 把流里的数据读取出来,并构造成位图对象


  4. 把位图对象显示至ImageView

ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);


  需要添加权限

<uses-permission android:name="android.permission.INTERNET"/>


网络请求

主线程阻塞

  在Android中,主线程被阻塞会导致UI停止刷新,用户体验将非常差,若主线程阻塞时间过长,就会抛出ANR(Application Not Responding,即应用无响应)异常。因此任何耗时操作都不应该在主线程进行,否则可能使主线程阻塞。因为网络请求属于耗时操作,如果网速很慢,线程会被阻塞,所以网络请求的代码不能写在主线程中。

消息传递机制

主线程又称UI线程,因为只有在主线程中才能刷新UI。如果需要在子线程中刷新UI,需要借助Handler的消息传递机制

主线程创建时,系统会为主线程创建一个Looper(ActivityThread中的main方法中依次调用Looper.prepareMainLooper(),Looper.loop()),而Looper对象在初始化时会创建一个与之关联的MessageQueue

如果是子线程的话,需要我们自己在子线程调用Looper.prepare()来为子线程创建一个Looper(Looper对象在初始化时仍会创建一个与之关联的MessageQueue),然后再调用Looper.loop()来启动这个Looper

Looper.loop()使用一个死循环不断的取出MessageQueue中的Message,然后将Message分发给曾经发送它的Handler进行处理(如果MessageQueue中没有Message,loop()方法会暂时阻塞,实际上Android系统的UI线程始终处于loop死循环中,一旦退出这个消息循环,App也就退出了)

Handler收到Message后会回调它的handleMessage()来处理这条Message。如果这个handleMessage()方法运行在主线程中,就可以刷新UI

/**
* 调用默认的构造器new一个Handler会将它与所在的线程关联起来
* 如果Handler关联的线程没有Looper,就会抛出如下异常
* java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
* 这里是在主线程中直接new一个Handler,不会抛异常,且handleMessage()可以刷新UI
*/
android.os.Handler handler = new android.os.Handler(){

public void handleMessage(Message msg) {

}
};


在子线程中向Handler所在线程的MessageQueue里发送Message

Message msg = handler.obtainMessage();// 这样创建Message对象比直接new更节省空间
msg.obj = bm;  // obj字段可以赋值任何对象,用来携带数据
msg.what = 1;   // what字段相当于一个标签,用来区分出不同的Message,从而进行不同的处理
handler.sendMessage(msg);


通过switch语句区分不同的Message

public void handleMessage(android.os.Message msg) {
switch (msg.what) {
// 如果是1,说明是请求成功的Message
case 1:
ImageView iv = (ImageView) findViewById(R.id.iv);
Bitmap bm = (Bitmap) msg.obj;
iv.setImageBitmap(bm);
break;
case 2:
Toast.makeText(MainActivity.this, "请求失败", 0).show();
break;
}
}


加入缓存图片的功能

  读取服务器返回的流里的数据,把数据写到本地文件缓存起来

InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int len = 0;
while((len = is.read(b)) != -1){
fos.write(b, 0, len);
}
fos.close();


  读取缓存的数据,并构造成位图对象

Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());


  每次发送请求前检测一下在缓存中是否存在同名图片,如果存在,则读取缓存

Html源文件查看器

  发送GET请求

URL url = new URL(path);
//获取连接对象,此时还未建立连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置连接属性
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// 可以不写conn.connect();
// 如果不写conn.connect();,getResponseCode()会先建立连接,然后获得响应码
if(conn.getResponseCode() == 200){

}


  获取服务器返回的流,从流中把html源码读取出来

InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = is.read(b)) != -1){
//把读到的字节先写入字节数组输出流中存起来
bos.write(b, 0, len);
}
//把字节数组输出流中的内容转换成字符串
//Android系统默认使用utf-8编码
text = new String(bos.toByteArray());


乱码的处理

  乱码的出现是因为服务器端和客户端码表不一致所致

text = new String(bos.toByteArray(), "gb2312");// 手动指定码表


提交数据

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编码(这里用户名name使用了中文)

final String path = "http://192.168.1.104/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass;


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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: