package cgg.com.homework.NetUtil; import android.os.Environment; import java.io.File; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; /** * author: Wanderer * date: 2018/1/9 16:38 * email: none */ public class OkHttpUtil { private OkHttpClient okHttpClient; public OkHttpClient getInstance() { if(okHttpClient == null){ // 设置缓存目录 File okHttPCache = new File(Environment.getExternalStorageDirectory(), "cache"); // 设置缓存大小 int cacheSize = 10*1024*1024; synchronized (OkHttpUtil.class){ okHttpClient = new OkHttpClient.Builder() // 构建者 .connectTimeout(15, TimeUnit.SECONDS) // 连接超时 .readTimeout(15,TimeUnit.SECONDS) // 读取超时 .writeTimeout(15,TimeUnit.SECONDS) // 写入超时 .cache(new Cache(okHttPCache.getAbsoluteFile(),cacheSize)) // 设置缓存 .build(); // 闭环 } } return okHttpClient; } /** * get请求 */ public void doGet(String url, Callback callback){ // 获取OkHttpClient对象 OkHttpClient mHttpClient = getInstance(); // 获取Request对象 Request request = new Request.Builder().url(url).build(); // 获取Call对象 Call call = mHttpClient.newCall(request); // 执行异步请求 call.enqueue(callback); } /** * post请求 */ public void doPost(String url, Map<String,String> parameters,Callback callback){ // 获取OkHttpClient对象 OkHttpClient mHttpClient = getInstance(); // 获取构建者 FormBody.Builder builder = new FormBody.Builder(); // 遍历集合 for (String key: parameters.keySet()) { // 添加上传的参数 builder.add(key,parameters.get(key)); } // 获取Request对象 Request request = new Request.Builder().url(url).post(builder.build()).build(); // 获取Call Call call = mHttpClient.newCall(request); // 执行请求 call.enqueue(callback); } }
okHttpClient--post/get请求
最新推荐文章于 2024-07-02 10:02:55 发布