OkHttp框架
来源:互联网 发布:虚拟的社交知乎 编辑:程序博客网 时间:2024/05/17 06:16
依赖:compile 'com.squareup.okhttp3:okhttp:3.9.0' compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'权限: <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />public class HttpUtil { private static volatile HttpUtil httpUtil; private final OkHttpClient client; private Context context; private Handler handler = new Handler(Looper.getMainLooper()); private HttpUtil(Context context) { //缓存目录 File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024;//拦截器 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); client = new OkHttpClient.Builder() .addInterceptor(logging)// .addNetworkInterceptor(new CacheInterceptor())// .writeTimeout(20, TimeUnit.SECONDS)// .readTimeout(20, TimeUnit.SECONDS)// .cache(new Cache(sdcache,cacheSize)) .build(); this.context = context; } public static HttpUtil getInstance(Context context) { if (httpUtil == null) { synchronized (HttpUtil.class) { if (httpUtil == null) { httpUtil = new HttpUtil(context); } } } return httpUtil; } public void doPost(String url, Map<String, String> params, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } if (params != null && params.size() > 0) { FormBody.Builder builder = new FormBody.Builder(); params.put("client", "android"); for (Map.Entry<String, String> entry : params.entrySet()) { builder.add(entry.getKey(), entry.getValue()); } FormBody formBody = builder.build(); Request request = new Request.Builder().url(url).post(formBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final BaseBean baseBean = (BaseBean) new Gson().fromJson(response.body().string(), clazz); int code = baseBean.getCode(); if (code == 200) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { } } }); } } public void download(String url, Callback callback) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(callback); } public void doGet(String url, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } Request.Builder builder = new Request.Builder(); builder.url(url); final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); int code = baseBean.getCode(); if (code == 200) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { } } }); } /** * @param url * @param params * @param header * @param clazz * @param onNetListener */ public void doGet(String url, HashMap<String, String> params, HashMap<String, String> header, final Class clazz, final OnNetListener onNetListener) { //网络判断 if (!NetWorkUtil.isNetworkAvailable(context)) { Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show(); return; } Request.Builder builder = new Request.Builder(); if (params != null && params.size() > 0) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(url); sb.append("?"); sb.append(entry.getKey()); sb.append("="); sb.append(entry.getValue()); } url = sb.toString(); } builder.url(url); //添加请求头 if (params != null && header.size() > 0) { for (Map.Entry<String, String> entry : params.entrySet()) { builder.addHeader(entry.getKey(), entry.getValue()); } } final Request request = builder.build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { onNetListener.onError(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz); int code = baseBean.getCode(); if (code == 200) { handler.post(new Runnable() { @Override public void run() { try { onNetListener.onSuccess(baseBean); } catch (IOException e) { e.printStackTrace(); } } }); } else if (code == 400) { } else if (code == 300) { } } }); } /** * 上传 * * @param url * @param fileName */ public void uploadFile(String url, String fileName) { String file = Environment.getExternalStorageState() + "/" + fileName; RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); //创建RequestBody 设置类型等 RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", fileName, fileBody).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } /** * 下载 * * @param url */ public void download(String url) { Request request = new Request.Builder().url(url).build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }}public class NetWorkUtil { // check all network connect, WIFI or mobile public static boolean isNetworkAvailable(final Context context) { boolean hasWifoCon = false; boolean hasMobileCon = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE); NetworkInfo[] netInfos = cm.getAllNetworkInfo(); for (NetworkInfo net : netInfos) { String type = net.getTypeName(); if (type.equalsIgnoreCase("WIFI")) { if (net.isConnected()) { hasWifoCon = true; } } if (type.equalsIgnoreCase("MOBILE")) { if (net.isConnected()) { hasMobileCon = true; } } } return hasWifoCon || hasMobileCon; }}public class BaseActivity extends AppCompatActivity { private LinkedList<Activity> list = new LinkedList<>(); protected HttpUtil httpUtil; private ProgressDialog dialog; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); list.add(this); httpUtil = HttpUtil.getInstance(this); } protected void toast(String str) { Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } public void finshAll() { for (Activity ac : list) { if (!ac.isFinishing()) { ac.finish(); } } } /** * 显示进度条 */ protected void showPd() { dialog = new ProgressDialog(this); dialog.setMessage("正在加載..."); dialog.show(); } /** * 关闭进度条 */ protected void dismissPd() { if (dialog != null && !this.isFinishing()) { dialog.dismiss(); } }}public class LoggingInterceptor implements Interceptor { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Logger.i(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); Logger.i(String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); return response; }}
阅读全文
0 0
- oKhttp框架
- OkHTTP框架
- OKHttp框架
- OkHttp框架
- OkHttp框架
- OKHttp框架
- Android OkHttp封装 框架
- okHttp开发框架使用
- android OkHttp框架解析
- okhttp框架的封装
- okhttp框架的使用
- okhttp网络请求框架
- java-框架-OkHttp
- 网络请求框架OKHttp
- OkHttp网络请求框架
- Android OkHttp框架解析
- okhttp框架 工具类
- Android okHttp框架
- 几种委托指向函数的方式
- 实例开发聊天室 tcp协议
- HTML 练习题3
- shell学习之一---bash介绍
- Tensorflow——去噪自编码器
- OkHttp框架
- 如何在html中获取字符串长度,扩展css对标签内容多省略
- eclipse打不开jsp(其他文件参考jsp)文件的解决方法
- CSS实现单行、多行文本溢出显示省略号
- MApp
- xUtils框架网络获取
- ES6 字符串扩展
- MyBatis和Hibernate相比,优势在哪里?
- activiti流程图查看