安卓使用OkHttpClient进行网络请求

一般的安卓开发中,我们进行网络请求使用的都是HttpUrlClient。但使用起来有点繁琐。可以通过OkHttpClient减少代码量,源码为https://github.com/square/okhttp

OkHttpClient的使用非常简单,也可以分为同步和异步两种。

同步(Synchronous Get)

首先引入Okhttpclient的依赖包

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

然后在manifest文件中给应用程序访问网络的权限

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

由于android无法在主线程中访问网络,所以,我们必须新建一个异步加载类来进行网络请求,具体代码如下

package com.example.guolei.okhttp;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.test);
        new LoadOkHttpClientTask().execute("http://121.42.29.143/startup/index.php/Home/ItemComment/getAll/");
    }

    class LoadOkHttpClientTask extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(params[0])
                    .build();
            Response response = null;
            try {
                response = client.newCall(request).execute();
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;

        }


        @Override
        protected void onPostExecute(String s) {
            textView.setText(s);
        }
    }

}

异步(Asynchronous Get)

和同步的方式不同的是,异步的方式不需要异步加载类,它自己新建了一个工作线程来实现网络请求,并且有访问结束时可供回调的方法。具体代码如下所示,

package com.example.guolei.okhttp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.test);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://121.42.29.143/startup/index.php/Home/ItemComment/getAll/12899")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                textView.setText(response.body().string());

            }
        });
    }


}

你可能感兴趣的:(Android学习)