Android 对okhttp的封装
生活随笔
收集整理的這篇文章主要介紹了
Android 对okhttp的封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
不廢話,需求:根據服務器API封裝網絡請求,怎么辦?
?
簡單封裝okhttp的get,post,put,delete請求:
PersistentCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getApplicationContext()));HttpUtils.okHttpClient = new OkHttpClient.Builder().cookieJar(cookieJar).build();?
/*** 為HttpGet 的 url 方便的添加多個name value 參數。** @param url* @param params* @return*/public static String attachHttpGetParams(String url, LinkedHashMap<String, String> params) {Iterator<String> keys = params.keySet().iterator();Iterator<String> values = params.values().iterator();StringBuffer stringBuffer = new StringBuffer();stringBuffer.append("?");for (int i = 0; i < params.size(); i++) {String value = null;try {value = URLEncoder.encode(values.next(), "utf-8");} catch (Exception e) {e.printStackTrace();}stringBuffer.append(keys.next() + "=" + value);if (i != params.size() - 1) {stringBuffer.append("&");}}return url + stringBuffer.toString();}public static void HTTP_GET_IMPROVE(final String url, final HTTPInterface httpInterface, final int count) {Request request = builder.url(url).method("GET", null).build();//3.創建一個call對象,參數就是Request請求對象Call call = okHttpClient.newCall(request);//4.請求加入調度,重寫回調方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {httpInterface.onFailure(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code(); // Log.e("HTTP_GET_IMPROVE", " code=" + code + " url=" + url + " count=" + count);int myCount = count - 1;if (code != 200 && count > 0) {HTTP_GET_IMPROVE(url, httpInterface, myCount);} else {httpInterface.onResponse(call, response);}}});}public static void HTTP_POST_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {//1.創建OkHttpClient對象 // OkHttpClient okHttpClient = new OkHttpClient();//2.通過new FormBody()調用build方法,創建一個RequestBody,可以用add添加鍵值對//3.創建Request對象,設置URL地址,將RequestBody作為post方法的參數傳入 // Request request = new Request.Builder().url(url).post(requestBody).build();final Request request = builder.url(url).post(requestBody).build();//4.創建一個call對象,參數就是Request請求對象Call call = okHttpClient.newCall(request);//5.請求加入調度,重寫回調方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {httpInterface.onFailure(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code();int myCount = count - 1;if (code != 200 && count > 0) {HTTP_GET_IMPROVE(url, httpInterface, myCount);} else {// Log.e("TAG", "POST JSESSIONID= " + response.header("JSESSIONID"));httpInterface.onResponse(call, response);}}});}public static void HTTP_PATCH_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {//1.創建OkHttpClient對象 // OkHttpClient okHttpClient = new OkHttpClient();//2.創建Request對象,設置一個url地址(百度地址),設置請求方式。Request request = new Request.Builder().url(url).method("PATCH", requestBody).build();//3.創建一個call對象,參數就是Request請求對象Call call = okHttpClient.newCall(request);//4.請求加入調度,重寫回調方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {httpInterface.onFailure(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code();int myCount = count - 1;if (code != 200 && count > 0) {HTTP_GET_IMPROVE(url, httpInterface, myCount);} else {httpInterface.onResponse(call, response);}}});}public static void HTTP_PUT_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {//1.創建OkHttpClient對象 // OkHttpClient okHttpClient = new OkHttpClient();//2.創建Request對象,設置一個url地址(百度地址),設置請求方式。Request request = new Request.Builder().url(url).method("PUT", requestBody).build();//3.創建一個call對象,參數就是Request請求對象Call call = okHttpClient.newCall(request);//4.請求加入調度,重寫回調方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {httpInterface.onFailure(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code();int myCount = count - 1;if (code != 200 && count > 0) {HTTP_GET_IMPROVE(url, httpInterface, myCount);} else {httpInterface.onResponse(call, response);}}});}public static void HTTP_DELETE_IMPROVE(final String url, RequestBody requestBody, final HTTPInterface httpInterface, final int count) {//1.創建OkHttpClient對象 // OkHttpClient okHttpClient = new OkHttpClient();//2.通過new FormBody()調用build方法,創建一個RequestBody,可以用add添加鍵值對//3.創建Request對象,設置URL地址,將RequestBody作為post方法的參數傳入Request request = new Request.Builder().url(url).delete(requestBody).build();//4.創建一個call對象,參數就是Request請求對象Call call = okHttpClient.newCall(request);//5.請求加入調度,重寫回調方法call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {httpInterface.onFailure(call, e);}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code();int myCount = count - 1;if (code != 200 && count > 0) {HTTP_GET_IMPROVE(url, httpInterface, myCount);} else {httpInterface.onResponse(call, response);}}});}/***/public static void HTTPUploadImage(final String url, final String imagePath, final HTTPInterface httpInterface, final int count) {Log.e("imagePath", "HTTPUploadImage " + imagePath);File file = new File(imagePath);RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("files", imagePath, image).build();Request request = new Request.Builder().url(url).post(requestBody).build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {int code = response.code();int myCount = count - 1;if (code != 200 && count > 0) {HTTPUploadImage(url, imagePath, httpInterface, myCount);} else {httpInterface.onResponse(call, response);}}});}根據服務器的API封裝:
public static void outProduct(String token, String product_id, HttpUtils.HTTPInterface httpInterface) {RequestBody requestBody = new FormBody.Builder().add("token", token).add("product_id", product_id).build();String url = HttpUtils.OUT_PRODUCT;HttpUtils.HTTP_POST_IMPROVE(url, requestBody, httpInterface, HttpUtils.HTTP_TOTAL_COUNT);}
這樣的好處是網絡請求的API與具體的界面分離了,我之前寫代碼,每次寫完界面,再做界面的請求,導致很多界面有同樣的網絡請求,不停復制,修改代碼,浪費時間。封裝代碼也是一個程序員技術提升的體現。
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的Android 对okhttp的封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android 通过腾讯WebServi
- 下一篇: Android 简单实现订单模块类APP