网络请求,采用链式调用,支持一点到底。java
/** * get请求 */ public static GetRequest get(String url); /** * post请求和文件上传 */ public static PostRequest post(String url); /** * delete请求 */ public static DeleteRequest delete(String url) ; /** * 自定义请求 */ public static CustomRequest custom(); /** * 文件下载 */ public static DownloadRequest downLoad(String url) ; /** * put请求 */ public static PutRequest put(String url);
1.包含一次普通请求全部能配置的参数,真实使用时不须要配置这么多,按本身的须要选择性的使用便可<br/>
2.如下配置所有是单次请求配置,不会影响全局配置,没有配置的仍然是使用全局参数。<br/>
3.为单个请求设置超时,好比涉及到文件的须要设置读写等待时间多一点。<br/>
完整参数GET示例:android
EasyHttp.get("/v1/app/chairdressing/skinAnalyzePower/skinTestResult") .baseUrl("http://www.xxxx.com")//设置url .writeTimeOut(30*1000)//局部写超时30s,单位毫秒 .readTimeOut(30*1000)//局部读超时30s,单位毫秒 .connectTimeout(30*1000)//局部链接超时30s,单位毫秒 .headers(new HttpHeaders("header1","header1Value"))//添加请求头参数 .headers("header2","header2Value")//支持添加多个请求头同时添加 .headers("header3","header3Value")//支持添加多个请求头同时添加 .params("param1","param1Value")//支持添加多个参数同时添加 .params("param2","param2Value")//支持添加多个参数同时添加 //.addCookie(new CookieManger(this).addCookies())//支持添加Cookie .cacheTime(300)//缓存300s 单位s .cacheKey("cachekey")//缓存key .cacheMode(CacheMode.CACHEANDREMOTE)//设置请求缓存模式 //.okCache()//使用模式缓存模式时,走Okhttp缓存 .cacheDiskConverter(new GsonDiskConverter())//GSON-数据转换器 //.certificates()添加证书 .retryCount(5)//本次请求重试次数 .retryDelay(500)//本次请求重试延迟时间500ms .addInterceptor(Interceptor)//添加拦截器 .okproxy()//设置代理 .removeHeader("header2")//移除头部header2 .removeAllHeaders()//移除所有请求头 .removeParam("param1") .accessToken(true)//本次请求是否追加token .timeStamp(false)//本次请求是否携带时间戳 .sign(false)//本次请求是否须要签名 .syncRequest(true)//是不是同步请求,默认异步请求。true:同步请求 .execute(new CallBack<SkinTestResult>() { @Override public void onStart() { //开始请求 } @Override public void onCompleted() { //请求完成 } @Override public void onError(ApiException e) { //请求错误 } @Override public void onSuccess(SkinTestResult response) { //请求成功 } });
Url能够经过初始化配置的时候传入EasyHttp.getInstance().setBaseUrl("http://www.xxx.com");
入口方法传入: EasyHttp.get("/v1/app/chairdressing/skinAnalyzePower/skinTestResult").baseUrl("http://www.xxxx.com")
若是入口方法中传入的url含有http或者https,则不会拼接初始化设置的baseUrl.
例如:EasyHttp.get("http://www.xxx.com/v1/app/chairdressing/skinAnalyzePower/skinTestResult")
则setBaseUrl()和baseUrl()传入的baseurl都不会被拼接。git
两种设置方式
.params(HttpParams params)
.params("param1","param1Value")//添加参数键值对github
HttpParams params = new HttpParams();
params.put("appId", AppConstant.APPID);
.addCommonParams(params)//设置全局公共参数json
.headers(HttpHeaders headers)
.headers("header2","header2Value")//添加参数键值对api
.addCommonHeaders(headers)//设置全局公共头缓存
支持get/post/delete/put等
链式调用的终点请求的执行方式有:execute(Class<T> clazz) 、execute(Type type)、execute(CallBack<T> callBack)三种方式,都是针对标准的ApiResult服务器
1.EasyHttp(推荐)
示例:cookie
方式一: //EasyHttp.post("/v1/app/chairdressing/skinAnalyzePower/skinTestResult") EasyHttp.get("/v1/app/chairdressing/skinAnalyzePower/skinTestResult") .readTimeOut(30 * 1000)//局部定义读超时 .writeTimeOut(30 * 1000) .connectTimeout(30 * 1000) .params("name","张三") .timeStamp(true) .execute(new SimpleCallBack<SkinTestResult>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onSuccess(SkinTestResult response) { if (response != null) showToast(response.toString()); } });
2.手动建立请求对象网络
//GetRequest 、PostRequest、DeleteRequest、PutRequest GetRequest request = new GetRequest("/v1/app/chairdressing/skinAnalyzePower/skinTestResult"); request.readTimeOut(30 * 1000)//局部定义读超时 .params("param1", "param1Value1") .execute(new SimpleCallBack<SkinTestResult>() { @Override public void onError(ApiException e) { } @Override public void onSuccess(SkinTestResult response) { } });
execute(Class<T> clazz)和execute(Type type)功能基本同样,execute(Type type)主要是针对集合不能直接传递Class
EasyHttp.get(url) .params("param1", "paramValue1") .execute(SkinTestResult.class)//很是简单直接传目标class //.execute(new TypeToken<List<SectionItem>>() {}.getType())//Type类型 .subscribe(new BaseSubscriber<SkinTestResult>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onNext(SkinTestResult skinTestResult) { showToast(skinTestResult.toString()); } });
网络请求会返回Subscription对象,方便取消网络请求
Subscription subscription = EasyHttp.get("/v1/app/chairdressing/skinAnalyzePower/skinTestResult") .params("param1", "paramValue1") .execute(new SimpleCallBack<SkinTestResult>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onSuccess(SkinTestResult response) { showToast(response.toString()); } }); //在须要取消网络请求的地方调用,通常在onDestroy()中 //EasyHttp.cancelSubscription(subscription);
带有进度框的请求,能够设置对话框消失是否自动取消网络和自定义对话框功能,具体参数做用请看请求回调讲解
ProgressDialogCallBack带有进度框的请求,能够设置对话框消失是否自动取消网络和自定义对话框功能,具体参数做用请看自定义CallBack讲解
IProgressDialog mProgressDialog = new IProgressDialog() { @Override public Dialog getDialog() { ProgressDialog dialog = new ProgressDialog(MainActivity.this); dialog.setMessage("请稍候..."); return dialog; } }; EasyHttp.get("/v1/app/chairdressing/") .params("param1", "paramValue1") .execute(new ProgressDialogCallBack<SkinTestResult>(mProgressDialog, true, true) { @Override public void onError(ApiException e) { super.onError(e);//super.onError(e)必须写不能删掉或者忘记了 //请求成功 } @Override public void onSuccess(SkinTestResult response) { //请求失败 } });
注:错误回调 super.onError(e);必须写
IProgressDialog mProgressDialog = new IProgressDialog() { @Override public Dialog getDialog() { ProgressDialog dialog = new ProgressDialog(MainActivity.this); dialog.setMessage("请稍候..."); return dialog; } }; EasyHttp.get(URL) .timeStamp(true) .execute(SkinTestResult.class) .subscribe(new ProgressSubscriber<SkinTestResult>(this, mProgressDialog) { @Override public void onError(ApiException e) { super.onError(e); showToast(e.getMessage()); } @Override public void onNext(SkinTestResult skinTestResult) { showToast(skinTestResult.toString()); } });
经过网络请求能够返回Observable,这样就能够很好的经过Rxjava与其它场景业务结合处理,甚至能够经过Rxjava的connect()操做符处理多个网络请求。例如:在一个页面有多个网络请求,如何在多个请求都访问成功后再显示页面呢?这也是Rxjava强大之处。
注:目前经过execute(Class<T> clazz)方式只支持标注的ApiResult结构,不支持自定义的ApiResult
示例:
Observable<SkinTestResult> observable = EasyHttp.get(url) .params("param1", "paramValue1") .execute(SkinTestResult.class); observable.subscribe(new BaseSubscriber<SkinTestResult>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onNext(SkinTestResult skinTestResult) { showToast(skinTestResult.toString()); } });
本库提供的文件下载很是简单,没有提供复杂的下载方式例如:下载管理器、断点续传、多线程下载等,由于不想把本库作重。若是复杂的下载方式,还请考虑其它下载方案。
文件目录若是不指定,默认下载的目录为/storage/emulated/0/Android/data/包名/files
文件名若是不指定,则按照如下规则命名:
1.首先检查用户是否传入了文件名,若是传入,将以用户传入的文件名命名
2.若是没有传入文件名,默认名字是时间戳生成的。
3.若是传入了文件名可是没有后缀,程序会自动解析类型追加后缀名
示例:
String url = "http://61.144.207.146:8081/b8154d3d-4166-4561-ad8d-7188a96eb195/2005/07/6c/076ce42f-3a78-4b5b-9aae-3c2959b7b1ba/kfid/2475751/qqlite_3.5.0.660_android_r108360_GuanWang_537047121_release_10000484.apk"; EasyHttp.downLoad(url) .savePath("/sdcard/test/QQ") .saveName("release_10000484.apk")//不设置默认名字是时间戳生成的 .execute(new DownloadProgressCallBack<String>() { @Override public void update(long bytesRead, long contentLength, boolean done) { int progress = (int) (bytesRead * 100 / contentLength); HttpLog.e(progress + "% "); dialog.setProgress(progress); if (done) {//下载完成 } ... } @Override public void onStart() { //开始下载 } @Override public void onComplete(String path) { //下载完成,path:下载文件保存的完整路径 } @Override public void onError(ApiException e) { //下载失败 } });
通常此种用法用于与服务器约定的数据格式,当使用该方法时,params中的参数设置是无效的,全部参数均须要经过须要上传的文本中指定,此外,额外指定的header参数仍然保持有效。
.upString("这是要上传的长文本数据!")//默认类型是:MediaType.parse("text/plain")
upString("这是要上传的长文本数据!", "application/xml") // 好比上传xml数据,这里就能够本身指定请求头
.upJson(jsonObject.toString())//上传json
.upBytes(new byte[]{})//上传byte[]
.requestBody(body)//上传自定义RequestBody
.upObject(object)//上传对象object
注:upString、upJson、requestBody、upBytes、upObject五个方法不能同时使用,当前只能选用一个
示例:
HashMap<String, String> params = new HashMap<>(); params.put("key1", "value1"); params.put("key2", "这里是须要提交的json格式数据"); params.put("key3", "也可使用三方工具将对象转成json字符串"); JSONObject jsonObject = new JSONObject(params); RequestBody body=RequestBody.create(MediaType.parse("xxx/xx"),"内容"); EasyHttp.post("v1/app/chairdressing/news/favorite") //.params("param1", "paramValue1")//不能使用params,upString 与 params 是互斥的,只有 upString 的数据会被上传 .upString("这里是要上传的文本!")//默认类型是:MediaType.parse("text/plain") //.upString("这是要上传的长文本数据!", "application/xml") // 好比上传xml数据,这里就能够本身指定请求头 //.upJson(jsonObject.toString()) //.requestBody(body) //.upBytes(new byte[]{}) //.upObject(object) .execute(new SimpleCallBack<String>() { @Override public void onError(ApiException e) { showToast(e.getMessage()); } @Override public void onSuccess(String response) { showToast(response); } });
支持单文件上传、多文件上传、混合上传,同时支持进度回调,
暂不实现多线程上传/分片上传/断点续传等高级功能
上传文件支持文件与参数一块儿同时上传,也支持一个key上传多个文件,如下方式能够任选
上传文件支持两种进度回调:ProgressResponseCallBack(线程中回调)和UIProgressResponseCallBack(能够刷新UI)
final UIProgressResponseCallBack listener = new UIProgressResponseCallBack() { @Override public void onUIResponseProgress(long bytesRead, long contentLength, boolean done) { int progress = (int) (bytesRead * 100 / contentLength); if (done) {//完成 } ... } }; EasyHttp.post("/v1/user/uploadAvatar") //支持上传新增的参数 //.params(String key, File file, ProgressResponseCallBack responseCallBack) //.params(String key, InputStream stream, String fileName, ProgressResponseCallBack responseCallBack) //.params(String key, byte[] bytes, String fileName, ProgressResponseCallBack responseCallBack) //.addFileParams(String key, List<File> files, ProgressResponseCallBack responseCallBack) //.addFileWrapperParams(String key, List<HttpParams.FileWrapper> fileWrappers) //.params(String key, File file, String fileName, ProgressResponseCallBack responseCallBack) //.params(String key, T file, String fileName, MediaType contentType, ProgressResponseCallBack responseCallBack) //方式一:文件上传 File file = new File("/sdcard/1.jpg"); //若是有文件名字能够不用再传Type,会自动解析到是image/* .params("avatar", file, file.getName(), listener) //.params("avatar", file, file.getName(),MediaType.parse("image/*"), listener) //方式二:InputStream上传 final InputStream inputStream = getResources().getAssets().open("1.jpg"); .params("avatar", inputStream, "test.png", listener) //方式三:byte[]上传 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); final byte[] bytes = baos.toByteArray(); //.params("avatar",bytes,"streamfile.png",MediaType.parse("image/*"),listener) //若是有文件名字能够不用再传Type,会自动解析到是image/* .params("avatar", bytes, "streamfile.png", listener) .params("file1", new File("filepath1")) // 能够添加文件上传 .params("file2", new File("filepath2")) // 支持多文件同时添加上传 .addFileParams("key", List<File> files) // 这里支持一个key传多个文件 .params("param1", "paramValue1") // 这里能够上传参数 .accessToken(true) .timeStamp(true) .execute(new ProgressDialogCallBack<String>(mProgressDialog, true, true) { @Override public void onError(ApiException e) { super.onError(e); showToast(e.getMessage()); } @Override public void onSuccess(String response) { showToast(response); } });
每一个请求前都会返回一个Subscription,取消订阅就能够取消网络请求,若是是带有进度框的网络请求,则不须要手动取消网络请求,会自动取消。
Subscription mSubscription = EasyHttp.get(url).execute(callback); ... @Override protected void onDestroy() { super.onDestroy(); EasyHttp.cancelSubscription(mSubscription); }
自动取消使用ProgressDialogCallBack回调或者使用ProgressSubscriber,就不用再手动调用cancelSubscription();
ProgressDialogCallBack:
EasyHttp.get(url).execute(new ProgressDialogCallBack());
ProgressSubscriber
EasyHttp.get(url).execute(SkinTestResult.class).subscribe(new ProgressSubscriber<SkinTestResult>(this, mProgressDialog) { @Override public void onError(ApiException e) { super.onError(e); showToast(e.getMessage()); } @Override public void onNext(SkinTestResult skinTestResult) { showToast(skinTestResult.toString()); } })
同步请求只须要设置syncRequest()方法
EasyHttp.get("/v1/app/chairdressing/skinAnalyzePower/skinTestResult") ... .syncRequest(true)//设置同步请求 .execute(new CallBack<SkinTestResult>() {});
//支持回调的类型能够是Bean、String、CacheResult<Bean>、CacheResult<String>、List<Bean> new SimpleCallBack<CacheResult<Bean>>()//支持缓存的回调,请看缓存讲解 new SimpleCallBack<CacheResult<String>>()//支持缓存的回调,请看缓存讲解 new SimpleCallBack<Bean>()//返回Bean new SimpleCallBack<String>()//返回字符串 new SimpleCallBack<List<Bean>()//返回集合
注:其它回调同理
cookie的内容主要包括:名字,值,过时时间,路径和域。路径与域一块儿构成cookie的做用范围,关于cookie的做用这里就再也不科普,本身能够去了解
cookie设置:
EasyHttp.getInstance() ... //若是不想让本库管理cookie,如下不须要 .setCookieStore(new CookieManger(this)) //cookie持久化存储,若是cookie不过时,则一直有效 ...
HttpUrl httpUrl = HttpUrl.parse("http://www.xxx.com/test"); CookieManger cookieManger = getCookieJar(); List<Cookie> cookies = cookieManger.loadForRequest(httpUrl);
PersistentCookieStore cookieStore= getCookieJar().getCookieStore(); List<Cookie> cookies1= cookieStore.getCookies();
Cookie.Builder builder = new Cookie.Builder(); Cookie cookie = builder.name("mCookieKey1").value("mCookieValue1").domain(httpUrl.host()).build(); CookieManger cookieManger = getCookieJar(); cookieManger.saveFromResponse(httpUrl, cookie); //cookieStore.saveFromResponse(httpUrl, cookieList);//添加cookie集合
HttpUrl httpUrl = HttpUrl.parse("http://www.xxx.com/test"); CookieManger cookieManger = EasyHttp.getCookieJar(); Cookie cookie = builder.name("mCookieKey1").value("mCookieValue1").domain(httpUrl.host()).build(); cookieManger.remove(httpUrl,cookie);
CookieManger cookieManger = EasyHttp.getCookieJar(); cookieManger.removeAll();
提供了用户自定义ApiService的接口,您只需调用call方法便可.
示例:
public interface LoginService { @POST("{path}") @FormUrlEncoded Observable<ApiResult<AuthModel>> login(@Path("path") String path, @FieldMap Map<String, String> map); } final CustomRequest request = EasyHttp.custom() .addConverterFactory(GsonConverterFactory.create(new Gson()))//自定义的能够设置GsonConverterFactory .params("param1", "paramValue1") .build(); LoginService mLoginService = request.create(LoginService.class); LoginService mLoginService = request.create(LoginService.class); Observable<ApiResult<AuthModel>> observable = request.call(mLoginService.login("v1/account/login", request.getParams().urlParamsMap)); Subscription subscription = observable.subscribe(new Action1<ApiResult<AuthModel>>() { @Override public void call(ApiResult<AuthModel> result) { //请求成功 } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { //请求失败 } });
提供默认的支持ApiResult结构,数据返回不须要带ApiResult,直接返回目标.
示例:
Observable<AuthModel> observable = request.apiCall(mLoginService.login("v1/account/login", request.getParams().urlParamsMap));