Tears_fg

导航

网络请求OkHttp的使用

 okHttp:

1.okHttp是squere公司出的,在Android4.0以后盛行

2.httpClient 在5.0中弃用,在6.0以Google的sdk中没有该api

3.httpUrlConnection 系统自带的,用的比较频繁

特点:连接效率高,可以异步和同步

需要导入两个jar包:

okhttp-3.0.0-RC1.jar  okio-1.6.0.jar(okhttp内部依赖okio)

package fanggao.qf.okhttptest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;

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

public class MainActivity extends AppCompatActivity {

    private TextView textview;
    private static final String url = "http://m2.qiushibaike.com/article/list/text?page=1";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btn_download);
        textview = (TextView) findViewById(R.id.tv_text);
    }
    /**
     * 点击下载数据
     * @param view
     */
    public void onClick(View view){
        //同步的方式,需要在子线程中运行,否则报错
   /*     new Thread(new Runnable() {
            @Override
            public void run() {
                getDataForGet();
            }
        }).start();*/
        //异步  ,不需要开启子线程
         getAsyncOkHttp();
    }
    /**
     * 异步:同时执行多个
     * 通过get请求获取数据
     *
     */
    private void getAsyncOkHttp() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        //异步:
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }
            @Override
            public void onResponse(Response response) throws IOException {
                final String string = response.body().String();
                Log.i("tag","------"+Thread.currentThread().getId());
                //只能在主线程中进行UI操作
                //在主线程中进行
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textview.setText(string);
                    }
                });
            }
        });
    }
    /**
     * 同步:一次执行一个
     * 通过get请求获取数据
     */
    private void getDataForGet() {
        try {
        //1.声明okhttp客户端
        OkHttpClient okHttpClient = new OkHttpClient();
        //2.构造request
            //1.声明构造器 ,设置请求方式,设置请求参数
        Request request = new Request.Builder().get().url(url).build();
        //3.通过客户端执行请求,获得response
            Response response = okHttpClient.newCall(request).execute();
            //4,判断响应是否成功
            if(response.isSuccessful()){
                //获得响应实体
                ResponseBody body = response.body();
                //获得string
               final  String string = body.string();
                //获得bytep[]
                byte[] bytes = body.bytes();
                //获得流
                InputStream inputStream = body.byteStream();
                //在主线程中进行
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textview.setText(string);
                    }
                });
            }
            Log.i("tag",Thread.currentThread().getName());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

现象:

 

posted on 2016-09-28 22:57  Tears_fg  阅读(1264)  评论(0编辑  收藏  举报