Android网络编程Okhttp3用法详解

 okHttp、volley、android-async-http对比:

  • volley是一个简单的异步http库,仅此而已。缺点是不支持同步,这点会限制开发模式;不能post大数据,所以不适合用来上传文件
  • android-async-http。与volley一样是异步网络库,但volley是封装的httpUrlConnection,它是封装的httpClient,而android平台不推荐用HttpClient了,所以这个库已经不适合android平台了。
  • okhttp是高性能的http库,支持同步、异步,而且实现了spdy、http2、websocket协议,api很简洁易用,和volley一样实现了http协议的缓存。

   okHttp介绍:

      通过上面的对比说明,让你不得不做出明智的选择,OkHttp是一个相对成熟的解决方案,据说Android4.4的源码中可以看到HttpURLConnection已经替换成OkHttp实现了,所以决定选择采用okhttp。

      官网地址:http://square.github.io/okhttp/

      官方API地址:https://www.51dev.com/android/66535

      github源码地址:https://github.com/square/okhttp

 okHttp主要类:

       1.)OkHttpClient.java

       2.)Request.java

       3.)Call.java

       4.)RequestBody.java

       5.)Response.java

 

OkHttp3使用:

1.在build.gradle中添加引用

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

2.在manifest中添加网络权限

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

3.创建一个OkHttpManager类

   OkHttpManager.java 属性

private static final String TAG = OkHttpManager.class.getSimpleName();  
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");//mdiatype 这个需要和服务端保持一致  
    //下面两个随便用哪个都可以  
    //    private static final MediaType MEDIA_TYPE_FILE = MediaType.parse("application/octet-stream");  
    private static final MediaType MEDIA_TYPE_FILE = MediaType.parse("image/jpg");  
    private static volatile OkHttpManager mInstance;//单利引用  
    private OkHttpClient mOkHttpClient;//okHttpClient 实例  
    private Handler okHttpHandler;//全局处理子线程和M主线程通信  

 OkhttpManager.java 构造函数

/**  
  * 初始化OkHttpManager  
  */  
  
public OkHttpManager(Context context) {  
     //初始化OkHttpClient  
     mOkHttpClient = new OkHttpClient().newBuilder()  
             .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间  
             .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间  
             .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间  
             .build();  
     //初始化Handler  
     okHttpHandler = new Handler(context.getMainLooper());  
 }  

   OkHttpManager.java 获取单利引用 这里用到了双重检查锁实现单例

/**  
 * 获取单例引用  
 *  
 * @return  
 */  
  
public static OkHttpManager getInstance(Context context) {  
    OkHttpManager inst = mInstance;  
    if (inst == null) {  
        synchronized (OkHttpManager.class) {  
            inst = mInstance;  
            if (inst == null) {  
                inst = new OkHttpManager(context.getApplicationContext());  
                mInstance = inst;  
            }  
        }  
    }  
    return inst;  
}  

4.实现okHttp同步请求
   okHttp get同步请求

  /** 
     * 1.1 okHttp get同步请求 
     * 
     * @param actionUrl 接口地址 
     * @param paramsMap 请求参数 
     */  
    public void getBySyn(String actionUrl, Map<String, Object> paramsMap) {  
        StringBuilder tempParams = new StringBuilder();  
        try {  
            //处理参数  
            int pos = 0;  
            for (String key : paramsMap.keySet()) {  
                if (pos > 0) {  
                    tempParams.append("&");  
                }  
                //对参数进行URLEncoder  
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key).toString(), "utf-8")));  
                pos++;  
            }  
            //补全请求地址  这里的Config.SERVER_ADDRESS改成自己的BaseUrl  
            String requestUrl = String.format("%s%s?%s", Config.SERVER_ADDRESS, actionUrl, tempParams.toString());  
            //创建一个请求  
            Request request = addHeaders().url(requestUrl).build();  
            //创建一个Call  
            final Call call = mOkHttpClient.newCall(request);  
            //执行请求  
            final Response response = call.execute();  
            response.body().string();  
        } catch (Exception e) {  
            Log.e(TAG, e.toString());  
        }  
    }  
span>  

okHttp post同步请求

/** 
 * 1.2 okHttp post同步请求 
 * 
 * @param actionUrl 接口地址 
 * @param paramsMap 请求参数 
 */  
public void postBySyn(String actionUrl, Map paramsMap) {  
    try {  
        //处理参数  
        StringBuilder tempParams = new StringBuilder();  
        int pos = 0;  
        for (String key : paramsMap.keySet()) {  
            if (pos > 0) {  
                tempParams.append("&");  
            }  
            tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key).toString(), "utf-8")));  
            pos++;  
        }  
        //补全请求地址  
        String requestUrl = String.format("%s%s", Config.SERVER_ADDRESS, actionUrl);  
        //生成参数  
        String params = tempParams.toString();  
        //创建一个请求实体对象 RequestBody  
        RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params);  
        //创建一个请求  
        final Request request = addHeaders().url(requestUrl).post(body).build();  
        //创建一个Call  
        final Call call = mOkHttpClient.newCall(request);  
        //执行请求  
        Response response = call.execute();  
        //请求执行成功  
        if (response.isSuccessful()) {  
            //获取返回数据 可以是String,bytes ,byteStream  
            Log.e(TAG, "response ----->" + response.body().string());  
        }  
    } catch (Exception e) {  
        Log.e(TAG, e.toString());  
    }  
}  

 okHttp post同步请求表单提交

/** 
 * 1.3 okHttp post同步请求表单提交 
 * 
 * @param actionUrl 接口地址 
 * @param paramsMap 请求参数 
 */  
private void postBySynWithForm(String actionUrl, Map paramsMap) {  
    try {  
        //创建一个FormBody.Builder  
        FormBody.Builder builder = new FormBody.Builder();  
        for (String key : paramsMap.keySet()) {  
            //追加表单信息  
            builder.add(key, paramsMap.get(key).toString());  
        }  
        //生成表单实体对象  
        RequestBody formBody = builder.build();  
        //补全请求地址  
        String requestUrl = String.format("%s%s", Config.SERVER_ADDRESS, actionUrl);  
        //创建一个请求  
        final Request request = addHeaders().url(requestUrl).post(formBody).build();  
        //创建一个Call  
        final Call call = mOkHttpClient.newCall(request);  
        //执行请求  
        Response response = call.execute();  
        if (response.isSuccessful()) {  
            Log.e(TAG, "response ----->" + response.body().string());  
        }  
    } catch (Exception e) {  
        Log.e(TAG, e.toString());  
    }  
}  

5.实现okHttp异步请求

  okHttp get异步请求

/** 
 * 2.1 okHttp get异步请求 
 * 
 * @param actionUrl 接口地址 
 * @param paramsMap 请求参数 
 * @param callBack  请求返回数据回调 
 * @return 
 */  
public void getByAsyn(String actionUrl, Map paramsMap, final OkHttpCallback callBack) {  
    StringBuilder tempParams = new StringBuilder();  
    try {  
        int pos = 0;  
        for (String key : paramsMap.keySet()) {  
            if (pos > 0) {  
                tempParams.append("&");  
            }  
            tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key).toString(), "utf-8")));  
            pos++;  
        }  
        //http://117.78.49.154:18083/userproduct/api/4.0.0/config/getConfig  
        String requestUrl = String.format("%s%s?%s", Config.SERVER_ADDRESS, actionUrl, tempParams.toString());  
        Log.i(TAG, "requestUrl=" + requestUrl);  
        final Request request = addHeaders().url(requestUrl).build();  
        final Call call = mOkHttpClient.newCall(request);  
        call.enqueue(new Callback() {  
            @Override  
            public void onFailure(Call call, IOException e) {  
                onFailedCallBack(e, callBack);  
            }  
  
            @Override  
            public void onResponse(Call call, Response response) throws IOException {  
                if (response.isSuccessful()) {  
                    try {  
                        Log.i(TAG, "onResponse response=" + response);  
                        String responseStr = response.body().string();  
                        Log.i(TAG, "onResponse responseStr=" + responseStr);  
                        JSONObject oriData = new JSONObject(responseStr.trim());  
                        ServerResponse serverResponse = ServerResponse.parseFromResponse(oriData);  
                        //回调  
                        onSuccessCallBack(oriData, serverResponse, callBack);  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        });  
    } catch (Exception e) {  
        Log.e(TAG, e.toString());  
    }  
}  

  okHttp post异步请求

    /** 
     * 2.2 okHttp post异步请求 
     * 
     * @param actionUrl 接口地址 
     * @param paramsMap 请求参数 
     * @param callBack  请求返回数据回调 
     * @return 
     */  
    public void postByAsyn(String actionUrl, Map paramsMap, final OkHttpCallback callBack) {  
        try {  
            StringBuilder tempParams = new StringBuilder();  
            int pos = 0;  
            for (String key : paramsMap.keySet()) {  
                if (pos > 0) {  
                    tempParams.append("&");  
                }  
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key).toString(), "utf-8")));  
                pos++;  
            }  
            String params = tempParams.toString();  
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params);  
            String requestUrl = String.format("%s%s", Config.SERVER_ADDRESS, actionUrl);  
            final Request request = addHeaders().url(requestUrl).post(body).build();  
            final Call call = mOkHttpClient.newCall(request);  
            call.enqueue(new Callback() {  
                @Override  
                public void onFailure(Call call, IOException e) {  
                    onFailedCallBack(e, callBack);  
                }  
  
                @Override  
                public void onResponse(Call call, Response response) throws IOException {  
                    if (response.isSuccessful()) {  
                        try {  
                            String responseStr = response.body().string();  
                            Log.i(TAG, "onResponse responseStr=" + responseStr);  
                            JSONObject oriData = new JSONObject(responseStr.trim());  
                            ServerResponse serverResponse = ServerResponse.parseFromResponse(oriData);  
  
                            onSuccessCallBack(oriData, serverResponse, callBack);  
                        } catch (Exception e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            });  
        } catch (Exception e) {  
            Log.e(TAG, e.toString());  
        }  
    }  

   okHttp post异步请求表单提交

  /** 
     * 2.3 okHttp post异步请求表单提交 
     * 
     * @param actionUrl 接口地址 
     * @param paramsMap 请求参数 
     * @param callBack  请求返回数据回调 
     * @return 
     */  
    public void postByAsynWithForm(String actionUrl, Map paramsMap, final OkHttpCallback callBack) {  
        try {  
            FormBody.Builder builder = new FormBody.Builder();  
            for (String key : paramsMap.keySet()) {  
                builder.add(key, paramsMap.get(key).toString());  
            }  
            RequestBody formBody = builder.build();  
            String requestUrl = String.format("%s%s", Config.SERVER_ADDRESS, actionUrl);  
            final Request request = addHeaders().url(requestUrl).post(formBody).build();  
            final Call call = mOkHttpClient.newCall(request);  
            call.enqueue(new Callback() {  
                @Override  
                public void onFailure(Call call, IOException e) {  
                    onFailedCallBack(e, callBack);  
                }  
  
                @Override  
                public void onResponse(Call call, Response response) throws IOException {  
                    if (response.isSuccessful()) {  
                        try {  
                            String responseStr = response.body().string();  
                            Log.i(TAG, "onResponse responseStr=" + responseStr);  
                            JSONObject oriData = new JSONObject(responseStr.trim());  
                            ServerResponse serverResponse = ServerResponse.parseFromResponse(oriData);  
  
                            onSuccessCallBack(oriData, serverResponse, callBack);  
                        } catch (Exception e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            });  
        } catch (Exception e) {  
            Log.e(TAG, e.toString());  
        }  
    }  

 接口OkHttpCallback .java实现

   public interface OkHttpCallback {  
        /** 
         * 响应成功 
         */  
        void onSuccess(JSONObject oriData, ServerResponse response);  
  
  
        /** 
         * 响应失败 
         */  
        void onFailure(IOException e);  
    }  

 

6.上传图片 带参数
 

public void postFiles(String actionUrl, Map paramsMap, Map fileMap, final OkHttpCallback callBack) {  
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);  
  
        //入参-字符串  
        for (Map.Entry entry : paramsMap.entrySet()) {  
            requestBody.addFormDataPart(entry.getKey().toString(), entry.getValue().toString());  
        }  
        //入参-文件  
        for (Map.Entry entry : fileMap.entrySet()) {  
            File file = (File) entry.getValue();  
            RequestBody fileBody = RequestBody.create(MEDIA_TYPE_FILE, file);  
            String fileName = file.getName();  
            requestBody.addFormDataPart(entry.getKey().toString(), fileName, fileBody);  
        }  
  
        Request request = addHeaders().url(actionUrl).post(requestBody.build()).build();  
        mOkHttpClient.newCall(request).enqueue(new Callback() {  
            @Override  
            public void onFailure(Call call, IOException e) {  
                onFailedCallBack(e, callBack);  
            }  
  
  
            @Override  
            public void onResponse(Call call, Response response) throws IOException {  
                Log.i(TAG, "onResponse response=" + response);  
                if (response.isSuccessful()) {  
                    try {  
                        String responseStr = response.body().string();  
                        Log.i(TAG, "onResponse responseStr=" + responseStr);  
                        JSONObject oriData = new JSONObject(responseStr.trim());  
                        ServerResponse serverResponse = ServerResponse.parseFromResponse(oriData);  
  
                        onSuccessCallBack(oriData, serverResponse, callBack);  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        });  
    }  

7.添加请求头

private Request.Builder addHeaders() {  
    Request.Builder builder = new Request.Builder()  
            //addHeader,可添加多个请求头  header,唯一,会覆盖  
            .addHeader("Connection", "keep-alive")  
            .addHeader("platform", "2")  
            .addHeader("phoneModel", Build.MODEL)  
            .addHeader("systemVersion", Build.VERSION.RELEASE)  
            .addHeader("appVersion", "3.2.0")  
            .header("sid", "eyJhZGRDaGFubmVsIjoiYXBwIiwiYWRkUHJvZHVjdCI6InFia3BsdXMiLCJhZGRUaW1lIjoxNTAzOTk1NDQxOTEzLCJyb2xlIjoiUk9MRV9VU0VSIiwidXBkYXRlVGltZSI6MTUwMzk5NTQ0MTkxMywidXNlcklkIjoxNjQxMTQ3fQ==.b0e5fd6266ab475919ee810a82028c0ddce3f5a0e1faf5b5e423fb2aaf05ffbf");  
    return builder;  
}  

8.成功与失败回调处理

    成功回调处理

private void onSuccessCallBack(final JSONObject oriData, final ServerResponse response, final OkHttpCallback callBack) {  
     //因为okhttp3 UI的处理不能在子线程中,要在主线程中,所以要这样写  
     okHttpHandler.post(new Runnable() {  
         @Override  
         public void run() {  
             if (null != callBack) {  
                 callBack.onSuccess(oriData, response);  
             }  
         }  
     });  
 }  

  失败回调处理

private void onFailedCallBack(final IOException e, final OkHttpCallback callBack) {  
        okHttpHandler.post(new Runnable() {  
            @Override  
            public void run() {  
                if (null != callBack) {  
                    callBack.onFailure(e);  
                }  
            }  
        });  
    }  

你可能感兴趣的:(Android网络编程Okhttp3用法详解)