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

最简易的网络框架封装(新手可看)

2016-09-07 15:50 513 查看
网络通信在Android上的重要性就不多说了。

demo就是获取到“https://www.baidu.com/”的HTML代码后显示在textview中,如下图:(源码在文章结尾)



涉及知识点

1、HTTP网络请求,HttpURLConnnection的使用

2、简单线程

3、定义接口,实现回调

如果仅仅实现这个功能需要的java代码绝对在10行以下,但是本片主要是讲一下简易框架的封装。

封装目的:

1、在同一个项目中,我们要执行网络操作可定不想要每次都编写一遍HTTP请求的代码。通常情况我们都会将这些网络操作提取到一个公共的类里面,并提供一个静态方法。

2、HTTP请求操作一般为耗时操作需要放入线程。

3、在线程中需要返回从服务器获取的数据,要使用java的回调机制。

框架搭建好之后,代码的调用如下。

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tvMain=(TextView)findViewById(R.id.tv_main);

HttpUtill.sendHttpRequest("https://www.baidu.com/", new HttpUtill.HttpCallbackListener() {
@Override
public void onSuccess(String response) {
tvMain.setText(response);
}

@Override
public void onError(Exception e) {
tvMain.setText(e.getMessage());
}
});
}


封装的代码也是非常简单:

public class HttpUtill {

//为了实现回调,定义一个接口
public interface HttpCallbackListener{

void onSuccess(String response);

void onError(Exception e);
}

public static void sendHttpRequest(final String mUrl,final HttpCallbackListener listener) {
//此处使用线程
new Thread(new Runnable(){
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(mUrl);
connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader((new InputStreamReader(in)));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if(listener!=null){
listener.onSuccess(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
if(listener!=null){
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();

}
}


源码下载地址:http://download.csdn.net/detail/double2hao/9624231
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android html java 网络 http