通用封装系列——OkHttp

来源:互联网 发布:淘宝双十一倒计时代码 编辑:程序博客网 时间:2024/06/05 22:50

为了帮助自己记忆,以及方便自己以后使用,将一些常用、通用的功能整理出来,如果能帮到大家,那就更好了。

该系列文章并不是技术解析贴,不会讲详细原理,属于工具类,直接拿走即可使用。


okHttp,这个几乎每个Android开发都知道的强大的开源工具,我在多个我个人或者公司的项目中都有使用,将其中一些通用的方法封装在一个工具类,以便复用。

首先先上github地址:https://github.com/square/okhttp

废话不多说了,直接上代码:

public class OkHttpHelper {    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");    private static final MediaType STREAM = MediaType.parse("application/octet-stream; charset=utf-8");    private static OkHttpClient okHttpClient;    private static OkHttpHelper okHttpHelper;    private OkHttpHelper(){        okHttpClient= new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS)                .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间                .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间                .build();;    }    //单例模式构造okhttp实例    public static OkHttpHelper getInstance(){        if (okHttpHelper == null) {            synchronized (OkHttpHelper.class) {                if (okHttpHelper == null) {                    okHttpHelper = new OkHttpHelper();                }            }        }        return okHttpHelper;    }    //同步方式发起网络请求    public static Response execute(Request request) throws IOException{        return okHttpClient.newCall(request).execute();    }    //异步方式发起网络请求    public static void enqueue(Request request, Callback responseCallback){        okHttpClient.newCall(request).enqueue(responseCallback);    }    /**     * get请求     * @param url 请求URL     * @return  服务器返回内容     */    public static String okHttpGet(String url){        Request request = new Request.Builder().url(url).build();        try {            Response response = execute(request);            if (response.isSuccessful()) {                String responseUrl = response.body().string();                return responseUrl;            } else {                return null;            }        }catch (IOException e){            return null;        }    }    /**     * post请求     *     * @param url 请求URL     * @param json json入参     * @return 服务器返回内容     */    public static String okHttpPost(String url, String json){        try {            RequestBody body = RequestBody.create(JSON, json);            Request request = new Request.Builder()                    .url(url)                    .post(body)                    .build();            Response response = execute(request);            if (response.isSuccessful()) {                return response.body().string();            }        } catch (IOException e){            e.printStackTrace();        }        return null;    }    /**     * post请求     * @param context 上下文     * @param url 请求URL     * @param map 键值类型入参     * @return 服务器返回内容     */    public static String okHttpPost(Context context, String url, Map<String, Object> map){        
try {            FormBody.Builder body = new FormBody.Builder();            if (map != null) {                // map 里面是请求中所需要的 key 和 value                for (Map.Entry entry : map.entrySet()) {                    body.add(entry.getKey().toString(), entry.getValue().toString());                }            }            Request request = new Request.Builder().url(url).post(body.build()).tag(context).build();            Response response = execute(request);            if (response.isSuccessful()) {                return response.body().string();            }        }catch (IOException e){            e.printStackTrace();        }

return null; } /** * 上次文件 * @param context 上下文 * @param map 键值类型入参 * @param file 要上传的文件 * @param url 请求URL */ public static void okHttpPostFile(Context context, Map<String, Object> map, File file, UploadCall uploadCall, String url) { // form 表单形式上传 MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM); if(file != null){ RequestBody body = RequestBody.create(STREAM, file); // 参数分别为, 请求key ,文件名称 , RequestBody requestBody.addFormDataPart("media", file.getName(), body); } if (map != null) { for (Map.Entry entry : map.entrySet()) { requestBody.addFormDataPart(entry.getKey().toString(), entry.getValue().toString()); } } Request request = new Request.Builder().url(url).post(requestBody.build()).tag(context).build(); enqueue(request,uploadCall); } /** * 下载文件 * @param url 请求URL * @param outPath 文件要保存的完整目录(包括文件名) * @return */ public static String okHttpLoadFile(String url, String outPath){// String outPath = Params.CACHE_FILE_LOCATION + picname; //获取请求对象 Request request = new Request.Builder().url(url).build(); //获取响应体 ResponseBody body = null; try { body = okHttpClient.newCall(request).execute().body(); } catch (IOException e) { e.printStackTrace(); } //获取流 InputStream in = body.byteStream(); //转化为bitmap Bitmap bitmap = BitmapFactory.decodeStream(in); try { saveBitmap(bitmap,outPath); } catch (FileNotFoundException e) { outPath = ""; } catch (IOException e){ outPath = ""; } return outPath; } abstract static class UploadCall implements Callback{ private final int SUCCESS = 1; private final int FAIL = 0; private int position; private Handler updateSendTypeHandler; private String json; public UploadCall(int position, Handler updateSendTypeHandler,String json){ this.position = position; this.updateSendTypeHandler = updateSendTypeHandler; this.json = json; } public UploadCall(){ } public void onGetResult(int state,Response response){} @Override public void onFailure(Call call, IOException e) { onGetResult(FAIL,null); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { onGetResult(SUCCESS,response); } else { onGetResult(FAIL,null); } } } public static void saveBitmap(Bitmap bitmap, String filePath) throws FileNotFoundException,IOException{ FileOutputStream fos = null; fos = new FileOutputStream(filePath); if (fos != null) { bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos); fos.close(); } }}

该工具类封装了普通的get请求,不同入参的post请求,以及文件上传和下载。

网上关于okhttp的封装有很多,我也是参考了很多前辈和大神的方式,总结出更适合自己用的用法,如有不同意见,欢迎指正。