HarmonyHttpClientHarmonyOS HTTP 網絡框架
HarmonyHttpClient是一個鴻蒙上使用的Http網絡框架,里面包含純Java實現(xiàn)的HttpNet,類似okhttp使用,支持同步和異步兩種請求方式;還有鴻蒙版retrofit,和Android版Retrofit相似的使用,解放雙手般優(yōu)雅使用注解、自動解析json
很遺憾,目前沒能直接發(fā)布bintray,DevEco Studio上傳bintray,gradle安裝不通過,所以如果要使用,clone下來,引入module即可
HttpNet基本和進階使用方式,可以進行合適的封裝,簡化請求邏輯
構建GET請求:和okhttp類似
RequestParams params = new RequestParams()
.put("userName","oscer")
.put("pwd","oschina");
Request request = new Request.Builder().encode("UTF-8")
.method("GET")
.timeout(13000)
.url("http://www.oschina.net")
.build();
構建POST請求:
//請求參數(shù) RequestParams params = new RequestParams() .put("userName","oscer") .putFile("fileName","file") .put("pwd","oschina"); //請求對象 Request request = new Request.Builder() .encode("UTF-8") .method("POST") .params(params) .timeout(13000) .url("http://www.oschina.net") .build();
POST JSON 請求構建:
Request request = new Request.Builder() .encode("UTF-8") .method("POST") .content(new JsonContent("json") .timeout(13000) .url("http://www.oschina.net") .build();
執(zhí)行請求:
//構建Http客戶端,這里可以進行全局static final HttpNetClient client = new HttpNetClient(); client.setProxy("192.168.1.1",80);//您也可以開啟該客戶端全局代理 client.addInterceptor(new Interceptor() { /* 攔截器在執(zhí)行請求前都會走到這一步,如果是同步的,就是當前線程,如果是異步,就是子線程 * 因此可以在這里動態(tài)添加全局Cookie或其它Header之類的 * 進階使用:如果要求對所有接口Form表單進行全局加密,也可以在這里執(zhí)行 */ @Override public void intercept(Request request) { Log.e("請求攔截器當前線程: " + Thread.currentThread().getName() + " -- " + request.url()); } }); //執(zhí)行異步請求 client.newCall(request) //如果采用上傳文件方式,可以在這里開啟上傳進度監(jiān)控 .intercept(new InterceptListener() { @Override public void onProgress(final int index, final long currentLength, final long totalLength) { Log.e("當前進度", " -- " + ((float) currentLength / totalLength) * 100); } }) .execute(new Callback() { @Override public void onResponse(Response response) { String body = response.getBody();//getBody()和toStream()是互斥的 InputStream is = response.toStream();//如果采用下載,可以在這里監(jiān)聽下載進度 } @Override public void onFailure(Exception e) { Log.e("onFailure " + e.getMessage()); } }); // 也可以在子線程中執(zhí)行同步請求,如果有幾個接口需要進行順序請求,此方法最佳 try { Response response = client.newCall(request).execute(); String body = response.getBody(); }catch (Exception e){ e.printStackTrace(); }
Retrofit使用方式,底層網絡實現(xiàn)基于前面的 HttpNetClient,基于運行時注解添加請求配置,UI切換使用鴻蒙EventHandler
// 構建請求java接口,采用動態(tài)代理+注解實現(xiàn),服務器返回什么,Call<服務器返回json對應的Java bean>即可 public interface LoginService { //普通POST,方法名添加請求方法注解POST、GET、DELETE、Header等,方法參數(shù)添加Form表單注解 @Headers({"Cookie:cid=adcdefg;"})//靜態(tài)Header @POST("api/users/login") Call<BaseModel<User>> login(@Form("email") String email, @Form("pwd") String pwd, @Form("versionNum") int versionNum, @Form("dataFrom") int dataFrom); // 上傳文件 @POST("action/apiv2/user_edit_portrait") @Headers("Cookie:xxx=hbbb;")//上傳文件注解 Call<String> postAvatar(@File("portrait") String file); //JSON POST @POST("action/apiv2/user_edit_portrait") @Headers("Cookie:xxx=hbbb;") Call<String> postJson(@Json String file);//如果是Json POST,這么使用即可 //PATCH @PATCH("mobile/user/{uid}/online")//動態(tài)修改url路徑 Call<ResultBean<String>> handUp(@Path("uid") long uid); }
執(zhí)行請求
public static final String API = "http://www.oschina.net/"; public static Retrofit retrofit = new Retrofit(); retrofit.registerApi(API);//注冊api //進階使用,假設服務器返回來的json內容是aes加密的,那么可以添加轉化器,攔截響應,aes解密后再返回,此方法一定在子線程執(zhí)行,直接執(zhí)行耗時操作 retrofit.setConverterFactory(new ConverterFactory() { @Override public void convert(com.haibin.retrofit.Response response) { response.setBodyString("{json}");//攔截響應數(shù)據(jù),修改內容,如aes解密后再返回 Log.e("響應轉換器當前線程: " + Thread.currentThread().getName()); } }); //執(zhí)行異步請求,異步請求可以直接在UI線程執(zhí)行 retrofit.from(LoginService.class) .login("[email protected]", "123456", 2, 2); .withHeaders(Headers...)//動態(tài)添加某些Header .execute(new Callback<BaseModel<User>>() { @Override public void onResponse(Response<BaseModel<User>> response) { //回調是切換在UI線程,可直接更新界面,自動解析body,就是BaseModel<User>,需要判斷body為不為null } @Override public void onFailure(Exception e) { } }); //當然也支持同步請求,順序請求N個接口的最佳方法,解決邏輯嵌套,這里只能在子線程執(zhí)行 Response<BaseModel<User>> response = retrofit.from(LoginService.class) .login("[email protected]", "123456", 2, 2); .withHeaders(Headers...) .execute();
評論
圖片
表情
