Android OkHttp的封装使用
16lz
2021-01-23
1.先看原始的请求过程
以下是请求过程的使用示例。
private void useOkHttpSendRequest(){OkHttpClient client = new OkHttpClient();RequestBody body = new FormBody.Builder().add("InfoOne", mInfoOneEditText.getText().toString()).add("InfoTwo", mInfoTwoEditText.getText().toString).build();final Request request = new Request.Builder().url(UrlCons.YOUR_URL).post(body).build();Call call = client.newCall(request);call.enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e){}@Overridepublic void onResponse(Call call, Response response) throws IOException{if (response.isSuccessful()) {//This is in the sub-thread, we shuold transport the data to the main threadString responseBody = response.body().string();}}});}
没有封装的方法不好用。需要进行封装。
在APP中可以创建全局变量,使整个APP都用这个变量。参考:https://www.cnblogs.com/maoIT/p/3835833.html
如下:
此时对其进行封装,新建几个类。
//The class to deal with the OkHttpCallbackpublic abstract class OkHttpCallBack implements CallBack{public abstract void onSuccess(final Call call, JSONObject jsonObject);@Overridepublic void onResponse(Call call, Response response) throws IOException{if (response != null) {if (response.isSuccessful()) {try{String str = response.body().string().trim();JSONObject object = (JSONObject)new JSONTokener(str).nextValue();if (object != null) {onSuccess(call, object);}els{onFailure(call, null);}}catch{e.printStackTrace();}}else{onFailure(call, null);}}}@Overridepublic void onFailure(Call call, IOException e){}}
//OkHttp Core Classpublic class OkHttpUtil{private static OkHttpClient mOkHttpClient = null;//Call this method in the Application class. ---> onCreate() method.//Thus we can get only one instance of httpClient in the whole app. public static void init(){if (mOkHttpClient == null) {OkHttpClient.Builder builder = new OkHttpClient().newBuilder().connectTimeout(5000, TimeUnit.MILLISECOND).readTimeout(5000, TimeUnit.MILLISECOND).writeTimeout(5000, TimeUnit.MILLISECOND);mOkHttpClient = builder.build();}}//If GET method needs some other params, just need to add a HaspMap. Refer to:https://www.imooc.com/video/18685public static void get(String url, OkHttpCallback okHttpCallback){Call call = null;try{Request request = new Request.Builder().url(url).build();call = mOkHttpClient.newCall(request);call.enqueue(okHttpCallback);}catch(IOException ex){ex.printStackTrace();}}public static void post(String url, OkHttpCallback okHttpCallback, HashMap bodyMap){Call call = null;try{FormBody.Builder builder = new FormBody.Builder();for (HashMap.Entry entry : bodyMap.entrySet()) {builder.add(entry.getKey(), entry.getValue());}RequestBody body = builder.build();Request request = new Request.Builder().post(body).url(url).build();call = mOkHttpClient.newCall(request);call.enqueue(okHttpCallback);}catch(IOException ex){ex.printStackTrace();}}}
public abstract class ApiUtil {private ApiListener mApiListener = null;private String mStatus;private OkHttpCallback mSendListener = new OkHttpCallback(){@Overridepublic void onSuccess(Call call, Response response){mStatus = response.optString("status");if (isSuccess()) {try{parseData(response);mApiListener.success(ApiUtil.this);}catch(IOException e){e.printStackTrace();}}else{mApiListener.failrure(ApiUtil.this);}}@Overridepublic void onFailure(Call call, IOException e){mApiListener.failrure(ApiUtil.this);}}public boolean isSuccess(){return "0".equals(mStatus) || "200".equals(mStatus); }protected abstract void parseData(JSONObject jsonObject) throws Exception;protected abstract String getUrl();//Send GET request//Listener: Tell the app whether the GET reqeust is success.private void get(ApiListener listener){mApiListener = listener;OkHttpUtil.get(getUrl(), mSendListener);}private HashMap mBodyMap = new HashMap<>();public void addParams(String key, String value){mBodyMap.put(key, value);}//Send POST request//Listener: Tell the app whether the POST reqeust is success.private void post(ApiListener listener){mApiListener = listener;OkHttpUtil.post(getUrl(), mSendListener, mBodyMap);}}
public interface ApiListener {//Request successvoid succss(ApiUtil apiUtil);//Request failedvoid failrure(ApiUtil apiUtil);}
以下是测试GET的API
public class TestGetBookApi extends ApiUtil{public String mResponse;@Overrideprotected String getUrl(){return Url.IP + "/api/v1/books";}protected void parseData(JSONObject jsonObject){mResponse = jsonObject.toString();}}
以下是POST的API
public class TestPostBookApi extends ApiUtil{public String mResponse;public TestGetBookApi(String bookName, String bookInfo){addParams("bookName", bookName);addParams("bookInfo", bookInfo);}@Overrideprotected String getUrl(){return Url.IP + "/api/v1/books";}protected void parseData(JSONObject jsonObject){mResponse = jsonObject.toString();}}
以下是在Activity中进行调用测试
//Use the apipublic class TestActivity extends Activity{private void processGetApi(){new TestGetBookApi().get(new ApiListener() {@Overridepublic void success(ApiUtil apiUtil){TestGetBookApi api = (TestGetBookApi)apiUtil;String response = api.mResponse;parseResponse(response);}@Override void failrure(ApiUtil apiUtil){}});};//The parse the responsepublic void parseResponse(Response response){}private void processPostApi(){new TestPostBookApi(mBookNameEdit.getText().toString(),mBookInfoEdit.getText().toString()).post(new ApiListener(){@Overridepublic void success(ApiUtil apiUtil){Log.d(TAG, "---apiUtil = " + apiUtil);}@Override void failrure(ApiUtil apiUtil){}});}}
详细博客参考来源:https://www.imooc.com/video/18688
更多相关文章
- android 下载图片保存在sdcard并显示可拖动缩放
- android保存Bitmap图片到指定文件夹示例
- ubuntu ffmpeg 4.0.1 android 编译过程记录
- Android培训班(89)内核解压过程2
- Android 图片水平显示 类Gallery效果
- android在grid组件中加入添加删除图片按钮
- Android bootanimation制作过程
- java|android加载src路径下面的图片文件
- android中得到颜色,图片资源的方式