一、添加依赖
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.3.0' // 后面需要用到
添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
二、创建数据的实体类
三、创建描述网络请求的借口----采用“注解”描述
public interface GetRequestInterface {
@FormUrlEncoded
@POST("rest/v1.0/openapi/bar/{last}")
Call<BaseEntity<MyInfo>> postCall(@Path("last") String last, @FieldMap Map<String, String> map);
}
注:上述第一个参数last是接口的最后一部分,后面的map是把所有参数装进一个map集合里传过来
public class MainModelImp implements MainModel {
@Override
public void getDataFromNet(Map map, final OnDataListener listener) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.yjcul.com:8081/BAR/")
.addConverterFactory(GsonConverterFactory.create())
.build();
GetRequestInterface request = retrofit.create(GetRequestInterface.class);
Call call = request.postCall("getDeviceState", map);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
Log.e("tag", "++++>" + response.body());
listener.getData(response.body());
}
@Override
public void onFailure(Call call, Throwable t) {
listener.getData("ERROR");
}
});
}
@Override
public void stopRequest() {
Log.e("tag", "停止网路请求");
}
}