导言
现在虽然是多端平台开发的天下,但做Iot开发主要在安卓系统下,当然不排除以后的什么鸿蒙系统(至于能不能成大器这另一回事)。做Iot开发主要就是解决设备孤岛的问题,就是怎么将设备的数据上传到服务器是。传统的就http(s)或MQ这两套板斧,不过其实MQ也是基于http(s),只是由于其已经大多封装好调用直连所以是俺等懒人的必选之一。不过用MQ又要部署太多的事情,为几个简单去部署一堆事情,俺乐意其时间也不乐意,好吧!那用回http(s),虽然安卓的http传输还是可以,不过刚接触到一套Retrofit2框架。感觉不错,于是向大伙推荐一下吧。
它就是是一直雄霸在开源框架的TOP 1 的 Retrofit
Retrofit的前世今生
Retrofit其实是一款基于OkHttp的框架,它的底层就是OkHttp,OkHttp这个老朋友就不多解释了。。
Retrofit的优点
①超级解耦
②可以配置不同HttpClient来实现网络请求
③支持同步、异步和RxJava
④可以配置不同的反序列化工具来解析数据,如:json、xml
⑤请求速度快,使用非常方便灵活
使用方法
官网地址:https://square.github.io/retrofit/
引入依赖:
implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit依赖
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//可选依赖,解析json字符所用
网络权限:
<uses-permission android:name="android.permission.INTERNET" />
POST&GET方式:
GET
String baseURL="https://www.BAIDU.com/";
@GET("json?cid=60")//查询参数
Call<ResponseBody> getData();//获得数据//获取Retrofit对象
Retrofit retrofit = new Retrofit.Builder().baseUrl(MyServer.baseURL).build();
//通过Retrofit获取接口服务对象
MyServer server = retrofit.create(MyServer.class);
//接口对象调用其方法获取call对象
Call<ResponseBody> data = server.getData();
//call执行请求
data.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String json = response.body().string();
Log.e(TAG, "onFailure: " + response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});POST
String URL = "http://www.baidu.com/";//必须以反斜杠结尾
public interface MyServer {
//POST("search?") POST("search")相同
//@Field("key") String value post请求用来提交参数的
//@FormUrlEncoded post请求提交form表单的时候如果有参数,需要填加这个注解,用来将提交的参数编码
//post请求不提交参数,不要加,
//如果有提交的参数,没有加@FormUrlEncoded
//@Field和@FieldMap一样,@FieldMap只不过是把一个一个的参数,合成一个map
@POST("search?")
@FormUrlEncoded
Call<ResponseBody> postData1(@Field("key") String appKey,@Field("name") String appKey);
@POST("search")
@FormUrlEncoded
Call<ResponseBody> postData2(@FieldMap Map<String,Object> map);
}
//POST异步
private void initPostEnqueue() {
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.URL)
.build();
//2.获取MyServer接口服务对象
MyServer myServer = retrofit.create(MyServer.class);
//3.获取Call对象
//方式一
Call<ResponseBody> call1 = myServer.postData1("908ca46881994ffaa6ca20b31755b675");
//方式二
//不用切换主线程了,因为Retrofit帮我们切过了
//okHttpClient需要自己切换主线程
Map<String,Object> map = new HashMap<>();
map.put("appKey","908ca46881994ffaa6ca20b31755b675");
Call<ResponseBody> call = myServer.postData2(map);
//4.Call对象执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.e("retrofit", "onResponse: "+result);
tv.setText(result);//默认直接回调主线程
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("retrofit", "onFailure: "+t.getMessage());
}
});
}请求的注释

String url_get = "http://gank.io/api/";
String url_post = "http://yun918.cn/study/public/index.php/";
String url_query = "https://www.wanandroid.com/";
String url_body = "https://www.wanandroid.com/";
String url_headers = "https://cdwan.cn/api/";
//get
@GET("data/%E7%A6%8F%E5%88%A9/20/2")
Call<GetBean> getData();
//post
@POST("data/%E7%A6%8F%E5%88%A9/20/2")
Call<GetBean> getData2();
//field
@POST("register")
@FormUrlEncoded
Call<PostBean> getData3(@Field("username") String username,
@Field("password") String password,
@Field("phone") String phone,
@Field("verify") String verify);
//query
@GET("project/list/1/json")
Call<QueryBean> getData4(@Query("cid") int cid);
//fieldMap
@POST("register")
@FormUrlEncoded
Call<PostBean> getData5(@FieldMap Map<String, String> map);
//queryMap
@GET("project/list/1/json?")
Call<QueryBean> getData6(@QueryMap Map<String, Object> map);
//body
@POST("user/login")
Call<BodyBean> getData7(@Body RequestBody requestBody);
//path
@GET("data/%E7%A6%8F%E5%88%A9/20/{page}")
Call<GetBean> getData8(@Path("page") int page);
//url
@GET
Call<GetBean> getData9(@Url String url_query);
//headers
@POST("cart/add")
@FormUrlEncoded
@Headers("X-Nideshop-Token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo1LCJpYXQiOjE1ODMxNjgzMDB9.aqdQNPdW8anMSqaqfAGWNPZxbb6j39tAaV-fOuzNhUM")
Call<CartBean> getData10(@Field("goodsId") String goodsId,
@Field("number") String number,
@Field("productId") String productId);
//header
@POST("cart/add")
@FormUrlEncoded
Call<CartBean> getData11(@Header("X-Nideshop-Token") String header);暂时就这些关键点,有时间再详述。。。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。