okhttp工具类封装

简介: okhttp工具类封装

一、工具类功能

  • 一般的get请求
  • 一般的post请求
  • 基于Http的文件上传
  • 文件下载
  • 加载图片
  • 支持请求回调,直接返回对象、对象集合
  • 支持session的保持

最后会对上述几个功能进行封装,完整的封装类的地址见:https://github.com/hongyangAndroid/okhttp-utils

使用前,对于Android Studio的用户,可以选择添加:

compile'com.squareup.okhttp:okhttp:2.4.0'

或者Eclipse的用户,可以下载最新的jar okhttp he latest JAR ,添加依赖就可以用了。

注意:okhttp内部依赖okio,别忘了同时导入okio:

gradle: compile'com.squareup.okio:okio:1.5.0'

最新的jar地址:okio the latest JAR

相当的强大的工具

packagesocketio.hd.com.clouddisc.utils;
importandroid.os.Handler;
importandroid.os.Looper;
importandroid.widget.ImageView;
importcom.google.gson.Gson;
importcom.google.gson.internal.$Gson$Types;
importcom.squareup.okhttp.Call;
importcom.squareup.okhttp.Callback;
importcom.squareup.okhttp.FormEncodingBuilder;
importcom.squareup.okhttp.Headers;
importcom.squareup.okhttp.MediaType;
importcom.squareup.okhttp.MultipartBuilder;
importcom.squareup.okhttp.OkHttpClient;
importcom.squareup.okhttp.Request;
importcom.squareup.okhttp.RequestBody;
importcom.squareup.okhttp.Response;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.lang.reflect.ParameterizedType;
importjava.lang.reflect.Type;
importjava.net.CookieManager;
importjava.net.CookiePolicy;
importjava.net.FileNameMap;
importjava.net.URLConnection;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Set;
/*** Created by zhy on 15/8/17.*/publicclassOkHttpClientManager{
privatestaticOkHttpClientManagermInstance;
privateOkHttpClientmOkHttpClient;
privateHandlermDelivery;
privateGsonmGson;
privatestaticfinalStringTAG="OkHttpClientManager";
privateOkHttpClientManager()
    {
mOkHttpClient=newOkHttpClient();
//cookie enabledmOkHttpClient.setCookieHandler(newCookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
mDelivery=newHandler(Looper.getMainLooper());
mGson=newGson();
    }
publicstaticOkHttpClientManagergetInstance()
    {
if (mInstance==null)
        {
synchronized (OkHttpClientManager.class)
            {
if (mInstance==null)
                {
mInstance=newOkHttpClientManager();
                }
            }
        }
returnmInstance;
    }
/*** 同步的Get请求** @param url* @return Response*/privateResponse_getAsyn(Stringurl) throwsIOException    {
finalRequestrequest=newRequest.Builder()
                .url(url)
                .build();
Callcall=mOkHttpClient.newCall(request);
Responseexecute=call.execute();
returnexecute;
    }
/*** 同步的Get请求** @param url* @return 字符串*/privateString_getAsString(Stringurl) throwsIOException    {
Responseexecute=_getAsyn(url);
returnexecute.body().string();
    }
/*** 异步的get请求** @param url* @param callback*/privatevoid_getAsyn(Stringurl, finalResultCallbackcallback)
    {
finalRequestrequest=newRequest.Builder()
                .url(url)
                .build();
deliveryResult(callback, request);
    }
/*** 同步的Post请求** @param url* @param params post的参数* @return*/privateResponse_post(Stringurl, Param... params) throwsIOException    {
Requestrequest=buildPostRequest(url, params);
Responseresponse=mOkHttpClient.newCall(request).execute();
returnresponse;
    }
/*** 同步的Post请求** @param url* @param params post的参数* @return 字符串*/privateString_postAsString(Stringurl, Param... params) throwsIOException    {
Responseresponse=_post(url, params);
returnresponse.body().string();
    }
/*** 异步的post请求** @param url* @param callback* @param params*/privatevoid_postAsyn(Stringurl, finalResultCallbackcallback, Param... params)
    {
Requestrequest=buildPostRequest(url, params);
deliveryResult(callback, request);
    }
/*** 异步的post请求** @param url* @param callback* @param params*/privatevoid_postAsyn(Stringurl, finalResultCallbackcallback, Map<String, String>params)
    {
Param[] paramsArr=map2Params(params);
Requestrequest=buildPostRequest(url, paramsArr);
deliveryResult(callback, request);
    }
/*** 同步基于post的文件上传** @param params* @return*/privateResponse_post(Stringurl, File[] files, String[] fileKeys, Param... params) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, files, fileKeys, params);
returnmOkHttpClient.newCall(request).execute();
    }
privateResponse_post(Stringurl, Filefile, StringfileKey) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, newFile[]{file}, newString[]{fileKey}, null);
returnmOkHttpClient.newCall(request).execute();
    }
privateResponse_post(Stringurl, Filefile, StringfileKey, Param... params) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, newFile[]{file}, newString[]{fileKey}, params);
returnmOkHttpClient.newCall(request).execute();
    }
/*** 异步基于post的文件上传** @param url* @param callback* @param files* @param fileKeys* @throws IOException*/privatevoid_postAsyn(Stringurl, ResultCallbackcallback, File[] files, String[] fileKeys, Param... params) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, files, fileKeys, params);
deliveryResult(callback, request);
    }
/*** 异步基于post的文件上传,单文件不带参数上传** @param url* @param callback* @param file* @param fileKey* @throws IOException*/privatevoid_postAsyn(Stringurl, ResultCallbackcallback, Filefile, StringfileKey) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, newFile[]{file}, newString[]{fileKey}, null);
deliveryResult(callback, request);
    }
/*** 异步基于post的文件上传,单文件且携带其他form参数上传** @param url* @param callback* @param file* @param fileKey* @param params* @throws IOException*/privatevoid_postAsyn(Stringurl, ResultCallbackcallback, Filefile, StringfileKey, Param... params) throwsIOException    {
Requestrequest=buildMultipartFormRequest(url, newFile[]{file}, newString[]{fileKey}, params);
deliveryResult(callback, request);
    }
/*** 异步下载文件** @param url* @param destFileDir 本地文件存储的文件夹* @param callback*/privatevoid_downloadAsyn(finalStringurl, finalStringdestFileDir, finalResultCallbackcallback)
    {
finalRequestrequest=newRequest.Builder()
                .url(url)
                .build();
finalCallcall=mOkHttpClient.newCall(request);
call.enqueue(newCallback()
        {
@OverridepublicvoidonFailure(finalRequestrequest, finalIOExceptione)
            {
sendFailedStringCallback(request, e, callback);
            }
@OverridepublicvoidonResponse(Responseresponse)
            {
InputStreamis=null;
byte[] buf=newbyte[2048];
intlen=0;
FileOutputStreamfos=null;
try                {
is=response.body().byteStream();
Filefile=newFile(destFileDir, getFileName(url));
fos=newFileOutputStream(file);
while ((len=is.read(buf)) !=-1)
                    {
fos.write(buf, 0, len);
                    }
fos.flush();
//如果下载文件成功,第一个参数为文件的绝对路径sendSuccessResultCallback(file.getAbsolutePath(), callback);
                } catch (IOExceptione)
                {
sendFailedStringCallback(response.request(), e, callback);
                } finally                {
try                    {
if (is!=null) is.close();
                    } catch (IOExceptione)
                    {
                    }
try                    {
if (fos!=null) fos.close();
                    } catch (IOExceptione)
                    {
                    }
                }
            }
        });
    }
privateStringgetFileName(Stringpath)
    {
intseparatorIndex=path.lastIndexOf("/");
return (separatorIndex<0) ?path : path.substring(separatorIndex+1, path.length());
    }
/*** 加载图片** //@param view* //@param url* @throws IOException*//* private void _displayImage(final ImageView view, final String url, final int errorResId){final Request request = new Request.Builder().url(url).build();Call call = mOkHttpClient.newCall(request);call.enqueue(new Callback(){@Overridepublic void onFailure(Request request, IOException e){setErrorResId(view, errorResId);}@Overridepublic void onResponse(Response response){InputStream is = null;try{is = response.body().byteStream();ImageUtils.ImageSize actualImageSize = ImageUtils.getImageSize(is);ImageUtils.ImageSize imageViewSize = ImageUtils.getImageViewSize(view);int inSampleSize = ImageUtils.calculateInSampleSize(actualImageSize, imageViewSize);try{is.reset();} catch (IOException e){response = _getAsyn(url);is = response.body().byteStream();}BitmapFactory.Options ops = new BitmapFactory.Options();ops.inJustDecodeBounds = false;ops.inSampleSize = inSampleSize;final Bitmap bm = BitmapFactory.decodeStream(is, null, ops);mDelivery.post(new Runnable(){@Overridepublic void run(){view.setImageBitmap(bm);}});} catch (Exception e){setErrorResId(view, errorResId);} finally{if (is != null) try{is.close();} catch (IOException e){e.printStackTrace();}}}});}*/privatevoidsetErrorResId(finalImageViewview, finalinterrorResId)
    {
mDelivery.post(newRunnable()
        {
@Overridepublicvoidrun()
            {
view.setImageResource(errorResId);
            }
        });
    }
//*************对外公布的方法************publicstaticResponsegetAsyn(Stringurl) throwsIOException    {
returngetInstance()._getAsyn(url);
    }
publicstaticStringgetAsString(Stringurl) throwsIOException    {
returngetInstance()._getAsString(url);
    }
publicstaticvoidgetAsyn(Stringurl, ResultCallbackcallback)
    {
getInstance()._getAsyn(url, callback);
    }
publicstaticResponsepost(Stringurl, Param... params) throwsIOException    {
returngetInstance()._post(url, params);
    }
publicstaticStringpostAsString(Stringurl, Param... params) throwsIOException    {
returngetInstance()._postAsString(url, params);
    }
publicstaticvoidpostAsyn(Stringurl, finalResultCallbackcallback, Param... params)
    {
getInstance()._postAsyn(url, callback, params);
    }
publicstaticvoidpostAsyn(Stringurl, finalResultCallbackcallback, Map<String, String>params)
    {
getInstance()._postAsyn(url, callback, params);
    }
publicstaticResponsepost(Stringurl, File[] files, String[] fileKeys, Param... params) throwsIOException    {
returngetInstance()._post(url, files, fileKeys, params);
    }
publicstaticResponsepost(Stringurl, Filefile, StringfileKey) throwsIOException    {
returngetInstance()._post(url, file, fileKey);
    }
publicstaticResponsepost(Stringurl, Filefile, StringfileKey, Param... params) throwsIOException    {
returngetInstance()._post(url, file, fileKey, params);
    }
publicstaticvoidpostAsyn(Stringurl, ResultCallbackcallback, File[] files, String[] fileKeys, Param... params) throwsIOException    {
getInstance()._postAsyn(url, callback, files, fileKeys, params);
    }
publicstaticvoidpostAsyn(Stringurl, ResultCallbackcallback, Filefile, StringfileKey) throwsIOException    {
getInstance()._postAsyn(url, callback, file, fileKey);
    }
publicstaticvoidpostAsyn(Stringurl, ResultCallbackcallback, Filefile, StringfileKey, Param... params) throwsIOException    {
getInstance()._postAsyn(url, callback, file, fileKey, params);
    }
publicstaticvoiddisplayImage(finalImageViewview, Stringurl, interrorResId) throwsIOException    {
//getInstance()._displayImage(view, url, errorResId);    }
publicstaticvoiddisplayImage(finalImageViewview, Stringurl)
    {
//getInstance()._displayImage(view, url, -1);    }
publicstaticvoiddownloadAsyn(Stringurl, StringdestDir, ResultCallbackcallback)
    {
getInstance()._downloadAsyn(url, destDir, callback);
    }
//****************************privateRequestbuildMultipartFormRequest(Stringurl, File[] files,
String[] fileKeys, Param[] params)
    {
params=validateParam(params);
MultipartBuilderbuilder=newMultipartBuilder()
                .type(MultipartBuilder.FORM);
for (Paramparam : params)
        {
builder.addPart(Headers.of("Content-Disposition", "form-data; name=\""+param.key+"\""),
RequestBody.create(null, param.value));
        }
if (files!=null)
        {
RequestBodyfileBody=null;
for (inti=0; i<files.length; i++)
            {
Filefile=files[i];
StringfileName=file.getName();
fileBody=RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//TODO 根据文件名设置contentTypebuilder.addPart(Headers.of("Content-Disposition",
"form-data; name=\""+fileKeys[i] +"\"; filename=\""+fileName+"\""),
fileBody);
            }
        }
RequestBodyrequestBody=builder.build();
returnnewRequest.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }
privateStringguessMimeType(Stringpath)
    {
FileNameMapfileNameMap=URLConnection.getFileNameMap();
StringcontentTypeFor=fileNameMap.getContentTypeFor(path);
if (contentTypeFor==null)
        {
contentTypeFor="application/octet-stream";
        }
returncontentTypeFor;
    }
privateParam[] validateParam(Param[] params)
    {
if (params==null)
returnnewParam[0];
elsereturnparams;
    }
privateParam[] map2Params(Map<String, String>params)
    {
if (params==null) returnnewParam[0];
intsize=params.size();
Param[] res=newParam[size];
Set<Map.Entry<String, String>>entries=params.entrySet();
inti=0;
for (Map.Entry<String, String>entry : entries)
        {
res[i++] =newParam(entry.getKey(), entry.getValue());
        }
returnres;
    }
privatestaticfinalStringSESSION_KEY="Set-Cookie";
privatestaticfinalStringmSessionKey="JSESSIONID";
privateMap<String, String>mSessions=newHashMap<String, String>();
privatevoiddeliveryResult(finalResultCallbackcallback, Requestrequest)
    {
mOkHttpClient.newCall(request).enqueue(newCallback()
        {
@OverridepublicvoidonFailure(finalRequestrequest, finalIOExceptione)
            {
sendFailedStringCallback(request, e, callback);
            }
@OverridepublicvoidonResponse(finalResponseresponse)
            {
try                {
finalStringstring=response.body().string();
if (callback.mType==String.class)
                    {
sendSuccessResultCallback(string, callback);
                    } else                    {
Objecto=mGson.fromJson(string, callback.mType);
sendSuccessResultCallback(o, callback);
                    }
                } catch (IOExceptione)
                {
sendFailedStringCallback(response.request(), e, callback);
                } catch (com.google.gson.JsonParseExceptione)//Json解析的错误                {
sendFailedStringCallback(response.request(), e, callback);
                }
            }
        });
    }
privatevoidsendFailedStringCallback(finalRequestrequest, finalExceptione, finalResultCallbackcallback)
    {
mDelivery.post(newRunnable()
        {
@Overridepublicvoidrun()
            {
if (callback!=null)
callback.onError(request, e);
            }
        });
    }
privatevoidsendSuccessResultCallback(finalObjectobject, finalResultCallbackcallback)
    {
mDelivery.post(newRunnable()
        {
@Overridepublicvoidrun()
            {
if (callback!=null)
                {
callback.onResponse(object);
                }
            }
        });
    }
privateRequestbuildPostRequest(Stringurl, Param[] params)
    {
if (params==null)
        {
params=newParam[0];
        }
FormEncodingBuilderbuilder=newFormEncodingBuilder();
for (Paramparam : params)
        {
builder.add(param.key, param.value);
        }
RequestBodyrequestBody=builder.build();
returnnewRequest.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }
publicstaticabstractclassResultCallback<T>    {
TypemType;
publicResultCallback()
        {
mType=getSuperclassTypeParameter(getClass());
        }
staticTypegetSuperclassTypeParameter(Class<?>subclass)
        {
Typesuperclass=subclass.getGenericSuperclass();
if (superclassinstanceofClass)
            {
thrownewRuntimeException("Missing type parameter.");
            }
ParameterizedTypeparameterized= (ParameterizedType) superclass;
return$Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }
publicabstractvoidonError(Requestrequest, Exceptione);
publicabstractvoidonResponse(Tresponse);
    }
publicstaticclassParam    {
publicParam()
        {
        }
publicParam(Stringkey, Stringvalue)
        {
this.key=key;
this.value=value;
        }
Stringkey;
Stringvalue;
    }
}
目录
相关文章
|
3月前
|
Android开发
SharePreference封装成工具类
SharePreference封装成工具类
124 1
|
4月前
|
缓存 Java Spring
Guava缓存工具类封装和使用
Guava缓存工具类封装和使用
113 0
|
6月前
|
Java
JavaMap工具类(MapUtils)
JavaMap工具类(MapUtils)
|
6月前
|
Java Apache
远程调用工具HttpClient工具类封装
java远程调用工具HttpClient工具类类封装
|
6月前
封装httpclient工具类
httpclient远程调用工具封装使用
|
6月前
|
JSON Java 网络安全
Java使用hutool工具类发送网络请求
Java使用hutool工具类发送网络请求
210 0
网络请求工具类WebServiceUtils
网络请求工具类WebServiceUtils
|
设计模式 缓存 监控
OKHttp3 从使用到原理分析
Okhttp3 是我们经常使用的一个网络框架,可扩展性强,支持 get 缓存, spdy、http2.0,gzip 压缩减少数据流量,同步和异步请求,连接池复用机制等特性让广大 android 开发者深爱不已,今天我就带大家从 Okhttp 简单使用,到各种好用拦截器原理了解 Okhttp3
1823 0
OKHttp3 从使用到原理分析
|
JSON Android开发 数据格式
RxJava+Retrofit示例 ,Retrofit 注解学习
RxJava+Retrofit示例 ,Retrofit 注解学习
170 0