# okhttpX **Repository Path**: pengxiao/okhttpX ## Basic Information - **Project Name**: okhttpX - **Description**: okhttpx注重项目实用性,是okHttp3.6.0的扩展,支持包括post请求在内的staleTime缓存,支持json字符串映射为Object。 - **Primary Language**: Android - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 3 - **Forks**: 1 - **Created**: 2017-03-30 - **Last Updated**: 2021-06-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #okhttpX ####okhttpX 是一个Android网络层框架,包装了okhttp3.x。 ``` 主要功能: 1.可以将JSON字符串转换为java对象 2.对post缓存支持,可以很随意设置接口缓存 ``` ###使用方法 #####1.初始化缓存目录 ``` public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); // 缓存目录 HttpClient.cachePath = getAppCacheDir() + File.separator + "httpCache"; } /** * 获取缓存目录 */ public String getAppCacheDir(){ String cachePath; if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) { cachePath = getExternalCacheDir().getPath(); } else { cachePath = getCacheDir().getPath(); } return cachePath; } } ``` #####2.实现自己的API服务,继承BaseHttpService。例如要实现一个UserSerive: ``` public class UserService extends BaseHttpService { private static UserService instance; private UserService() { } public static UserService getInstance() { if (instance == null) { instance = new UserService(); } return instance; } private static final String getUserById = "http://192.168.1.165:8080/test/user"; /** * 获取用户信息 */ public void getUserById(int userId, OnResponseListener listener) { Map map = getMap(); map.put("uid", userId); RequestParam param = getRequestParam(getUserById, map); ResultType resultType = getResultType(ResultType.Type.OBJECT, UserBean.class); CacheTime cacheTime = getCacheTime(TimeUnit.SECONDS, 10); executeRequest(param, resultType, cacheTime, listener); } } ``` #####3.使用UserService ``` private void testHttp() { UserService.getInstance().getUserById(13, new OnUIResponseListener(this, this) { @Override public void callUISuccess(ResultObject resultObject) { UserBean user = (UserBean) resultObject.getData(); tv_json.setText(user.getId() + " , " + user.getName()); } @Override public void callUIFail() { Toast.makeText(getApplicationContext(), "失败", Toast.LENGTH_SHORT).show(); } }); } ```