OkHttp 用法解析

来源:互联网 发布:破解软件论坛 编辑:程序博客网 时间:2024/06/05 20:22

一 简介

     学习完Volley框架, 开始学习OkHttp 网络框架。

     本文 是基于okhttp-3.2.0.jar 开发。

 首先下载jar 库,http://download.csdn.net/detail/shizhonghuo19870328/9861138

二  OkHttp 的重要参数和方法

     OkHttp 框架大部分是基于build 方式初始化。

      1.初始化 OkHttpClient

         OkHttpClient 最好用build 方式进行初始化。

   以下介绍OkHttpClient.build()提供的几个重要的方法:

   1)设置连接超时

public OkHttpClient.Builder connectTimeout(longtimeout,TimeUnit unit) 

   2)设置读取超时

public OkHttpClient.Builder readTimeout(long timeout, TimeUnit unit) 
     3)设置写入超时
public OkHttpClient.Builder writeTimeout(long timeout, TimeUnit unit)

   4)设置代理

public OkHttpClient.Builder proxy(Proxy proxy)

   5)设置缓存

public OkHttpClient.Builder cache(Cache cache)
     6) 设置DNS
public OkHttpClient.Builder dns(Dns dns)
7) 建立OkHttpClient
public OkHttpClient build()

2. 初始化Request

     Request 同样用build 方式进行初始化。
     以下介绍Request.build() 的重要方法。
     1) 设置URL
public Request.Builder url(HttpUrl url);
public Request.Builder url(String url);
public Request.Builder url(URL url);
2) 设置报头,会将原有的报头覆盖
public Request.Builder header(String name, String value);
3)设置报头,在原有的报头之后添加
public Request.Builder addHeader(String name, String value);
     4) 设置缓存控制
public Request.Builder cacheControl(CacheControl cacheControl);
     CacheControl也可以从build() 初始化。 
     默认情况下, 首先会从缓存区查询命令结果, 如果有合适的结果,则返回缓存的结果, 如果在缓存区找不到结果,则进行网络查询。
     public static final CacheControl FORCE_NETWORK, 这种设置 不去查询缓存,直接进行网络查询。
     public static final CacheControl FORCE_CACHE; 这种设置值查询缓存。
     5) 设置连接请求的方法
public Request.Builder get() {    return this.method("GET", (RequestBody)null);}
public Request.Builder head() {    return this.method("HEAD", (RequestBody)null);}
public Request.Builder post(RequestBody body) {    return this.method("POST", body);}
public Request.Builder delete(RequestBody body) {    return this.method("DELETE", body);}
public Request.Builder put(RequestBody body) {    return this.method("PUT", body);}
public Request.Builder patch(RequestBody body) {    return this.method("PATCH", body);}
注意哪些方法需要设置RequestBody。
这里介绍一下FormBody, FormBody继承了RequestBody。 适用于哪些字符类RequestBody, 用build() 进行初始化。
    public static final class Builder {        private final List<String> names = new ArrayList();        private final List<String> values = new ArrayList();        public Builder() {        }        public FormBody.Builder add(String name, String value) {            this.names.add(HttpUrl.canonicalize(name, " \"\':;<=>@[]^`{}|/\\?#&!$(),~", false, false, true, true));            this.values.add(HttpUrl.canonicalize(value, " \"\':;<=>@[]^`{}|/\\?#&!$(),~", false, false, true, true));            return this;        }        public FormBody.Builder addEncoded(String name, String value) {            this.names.add(HttpUrl.canonicalize(name, " \"\':;<=>@[]^`{}|/\\?#&!$(),~", true, false, true, true));            this.values.add(HttpUrl.canonicalize(value, " \"\':;<=>@[]^`{}|/\\?#&!$(),~", true, false, true, true));            return this;        }        public FormBody build() {            return new FormBody(this.names, this.values);        }    }


    6) 建立request 
    public Request build() 

3. 创建连接任务(call)并执行。

    OkHttp 框架需要将 request 和OkHttpClient建立一个RealCall, 由RealCall对连接请求进行调度和执行。
    我将一个call 理解为一个连接请求的任务。
    
    1) 创建连接任务
    Call call=mOkHttpClient.newCall(request);
    public Call newCall(Request request) {        return new RealCall(this, request);    }

2) 执行任务,调用回调
     public void enqueue(Callback responseCallback)
     参数Callback 是执行结果的回调。
     Callback 是一个接口, 需要我们自己实现。
public interface Callback {    void onFailure(Call var1, IOException var2);    void onResponse(Call var1, Response var2) throws IOException;}

onFailure()方法是执行失败的回调
onResponse()方法是执行成功的回调,Response  是返回的结果。

三 实例程序
public class MainActivity extends AppCompatActivity implements View.OnClickListener{    private Button send,postsend,sendfile,downloadfile;    private OkHttpClient mOkHttpClient;    private URL url;    /*public static final MediaType MEDIA_TYPE_MARKDOWN            = MediaType.parse("text/x-markdown; charset=utf-8");*/    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        mOkHttpClient=initHttpClient();        send=(Button)findViewById(R.id.send);        postsend=(Button)findViewById(R.id.postsend);        sendfile=(Button)findViewById(R.id.sendfile);        downloadfile=(Button)findViewById(R.id.downloadfile);        // 用activity 直接实现OnClickListener, 必须要有的设置        send.setOnClickListener(this);        postsend.setOnClickListener(this);        sendfile.setOnClickListener(this);        downloadfile.setOnClickListener(this);        try {            url = new URL("http://www.baidu.com");        } catch(MalformedURLException e){            e.printStackTrace();        }    }    public void onClick(View v){        switch(v.getId()){            case R.id.send:                send(url);                break;            case R.id.postsend:                post();                break;            case  R.id.sendfile:                //postAsynFile();                break;            case R.id.downloadfile:                downAsynFile();                break;        }    }    private OkHttpClient initHttpClient(){        File sdcache = getExternalCacheDir();        int cacheSize = 10 * 1024 * 1024;        OkHttpClient client =null;        //推荐使用OkHttpClient.Builder() 去建立client.        client=new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)                .readTimeout(5,TimeUnit.SECONDS).writeTimeout(5,TimeUnit.SECONDS)                .cache(new Cache(sdcache,cacheSize)).build();        return client;    }    /*    *执行get 命令     */    private void send(URL url){        Request request=new Request.Builder().url(url).get()                //.cacheControl(CacheControl.FORCE_NETWORK)   //缓存设置为每次都从网络重新获取                .build();        Call call=mOkHttpClient.newCall(request);        call.enqueue(new Callback(){            public void onFailure(Call var1, IOException var2){            }            public void onResponse(Call var1, Response var2) throws IOException{                if (null != var2.cacheResponse()) {                    String str = var2.cacheResponse().toString();                    Log.i("wangshu", "cache---" + str);                } else {                    var2.body().string();                    String str = var2.networkResponse().toString();                    Log.i("wangshu", "network---" + str);                }            }        });    }    /*    * 执行post 命令    */    private void post(){        //FormBody 继承了RequestBody        FormBody foramBody=new FormBody.Builder().add("user","Li")                .add("pass","123").build();        Request request=new Request.Builder().url("http://www.baidu.com")                .post(foramBody).build();        Call call=mOkHttpClient.newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String str = response.body().string();                Log.i("OKHttp", str);                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();                    }                });            }        });    }    /*    * 异步上传文件    */   /* private void postAsynFile(){        File file=new File("/sdcard/download.txt");        Request request=new Request.Builder()                .url("https://api.github.com/markdown/raw")                .post(RequestBody.create(MEDIA_TYPE_MARKDOWN,file))                .build();        mOkHttpClient.newCall(request).enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                Log.i("wangshu", response.body().string());            }        });    }*/   /*   * 异步下载文件   */    private void downAsynFile(){        String url="http://img.my.csdn.net/uploads/201603/26/1458988468_5804.jpg";        Request request=new Request.Builder().url(url).build();        Call call=mOkHttpClient.newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                InputStream inputStream=response.body().byteStream();                FileOutputStream fileOutputStream = null;                try {                    fileOutputStream=new FileOutputStream(new File("/sdcard/liyang.jpg"));                    byte[ ] buffer=new byte[2018];                    int len;                    while((len= inputStream.read(buffer))!= -1){                        fileOutputStream.write(buffer,0,len);                    }                    fileOutputStream.flush();                }catch (IOException e){                    e.printStackTrace();                }            }        });    }}