在之前的小案例中写过一篇使用HttpUrlConnection获取网络数据的例子。在OKhttp盛行的时代,当然要学会怎么使用它,本篇就对其基本使用做一个介绍,然后再使用它的接口回调的方式获取相同的数据。因为它封装的很好了,并不需要我们去做封装,只需要写少量的代码就可以获取到复杂的网络数据了。

一、OKhttp的最基本使用。

还是直接使用代码来说话:

1、添加依赖:

Github网址:https://github.com/square/okhttp

compile 'com.squareup.okhttp3:okhttp:3.5.0'

2、等待构建成功后:在主活动中直接使用它的API

1、创建布局文件:

xmlns:android="http://schemas.android.com/apk/res/android"              android:layout_width="match_parent"              android:layout_height="match_parent"              android:orientation="vertical" >            android:id="@+id/send_request"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Request" />            android:layout_width="match_parent"        android:layout_height="match_parent" >                    android:id="@+id/response"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    

2、主活动中的代码:

public class MainActivity extends Activity implements View.OnClickListener {    private Button sendRequest;    private TextView responseText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sendRequest = (Button) findViewById(R.id.send_request);        responseText = (TextView) findViewById(R.id.response);        sendRequest.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if (v.getId() == R.id.send_request) {            sendRequestWithOKHttp();        }    }    private void sendRequestWithOKHttp() {        // 开启线程来发起网络请求        new Thread(new Runnable() {            @Override            public void run() {                try {                    OkHttpClient client = new OkHttpClient();                    Request request = new Request.Builder()                            .url("http://www.baidu.com")                            .build();                    Response response = client.newCall(request).execute();                    String responseData = response.body().string();                    show(responseData);                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }    public void show(final String finalDatas){        runOnUiThread(new Runnable() {           @Override            public void run() {               responseText.setText(finalDatas);            }        });    }}

这样我们就成功获取到了网络的数据,运行程序我们可以看到:


二、使用OKhttp提供的接口回调

1、定义一个HttpUtils类。加入如下静态方法:

//使用OKhttp,OKhttp给封装好了回调,我们直接使用即可public static void sendOKHttpRequst(final String address, final okhttp3.Callback callback){    new Thread(new Runnable() {        @Override        public void run() {            OkHttpClient client = new OkHttpClient();            Request request = new Request.Builder()                    .url(address)                    .build();            client.newCall(request).enqueue(callback);        }    }).start();}

2、使用工具类,使用回调方法

//使用OKhttp工具类    findViewById(R.id.btn_okhttp).setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View v) {            HttpUtils.sendOKHttpRequst(address, new Callback() {                @Override                public void onFailure(Call call, IOException e) {                    //对异常情况处理                    Log.e("MainActivity","错误信息是" + e.toString());                }                @Override                public void onResponse(Call call, final Response response) throws IOException {                    //得到服务器返回的数据response                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            try {                                mTextView.setText(response.body().string());                            } catch (IOException e) {                                e.printStackTrace();                            }                        }                    });                }            });        }    });}

这里只需要给出主活动的代码即可~,因为封装的太好,我们只需要几行代码就可以完成功能。还需要注意的是,谷歌工程师给封装业务逻辑是在子线程执行的,因此我们要更新数据要在主线程执行。运行程序接口是一样的~


喜欢我的朋友可以关注我,本专栏不定期更新简单有趣的安卓小文~

对于OKHttp更高级的用法,以后会在Android Studio精彩案例专栏里面进行细致详细的分析



更多相关文章

  1. 一句话锁定MySQL数据占用元凶
  2. Android(安卓)数据库开发之事务
  3. Android(安卓)大图片裁切时遇到的问题
  4. android中的代码布局
  5. Android(安卓)sdcard媒体文件更新(程序控制刷新MediaStore数据库)
  6. 写了个Android聊天客户端框架,基本聊天功能、数据库、服务器都有
  7. Android用surface直接显示yuv数据(一)
  8. BitmapFactory类的decodeStream方法在网络超时或较慢的时候无法
  9. Android中通过代码改变系统文件都写权限

随机推荐

  1. 我是如何自学Android,资料分享(2015 版)
  2. Android(安卓)通过百度地图SDK 实现地图
  3. android ANR产生原因和解决办法
  4. SystemServer分析
  5. Android(安卓)系统框架介绍
  6. LeakCanary使用详细教程(附Demo)
  7. Android(安卓)创建定时任务
  8. Android中通过view.getContext获取Activi
  9. Android中JNI的使用方法
  10. Android(安卓)LayoutInflater深入分析及