[Android]OkHttp的使用

简介

Paste_Image.png

导包

~compile 'com.squareup.okhttp3:okhttp:3.6.0'~

Get

 public void doGet(View view) throws IOException {
        //OkHttpClient对象
        OkHttpClient okHttpClient=new OkHttpClient();
        Request.Builder builder=new Request.Builder();
        //构造request
        Request request = builder.get().url("http://www.imooc.com/").build();
        //request封装为call
        Call call = okHttpClient.newCall(request);
        //执行call
        //Response response = call.execute();//同步
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("MyTAG","onFailure:"+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("MyTAG","onResponse:"+response.body().string());
            }
        });
    }

AS中,CTRL+F12 查看Okhttp中的方法

onResponse执行在子线程:

InputStream inputStream=response.body().byteStream();

可以对文件进行IO操作(文件下载)

 @Override
            public void onResponse(Call call, final Response response) throws IOException {
                final String s=response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(s);
                    }
                });
            }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容