Retrofit网络获取能优点很多,最实用的就是不用进行麻烦的Json具体解析,简单,优化,高效率
原理解析:https://blog.csdn.net/u011311586/article/details/79716863
一、创建接口:
public interface MenuService {
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1
//通过Get注解,获取网络Jasn数据:
@GET("dish_list.php?stage_id=1&limit=20&page=1")
Call<JavaBean> getResualt();
}
二、创建javaBean类:
三、权限:
Retrofit:
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
butterknife:
implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'com.facebook.fresco:fresco:1.5.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
四.实例网络框架Retrofit:要与butternife联用:
public class MainActivity extends AppCompatActivity {
@BindView(R.id.rv)
RecyclerView rv;
@BindView(R.id.but)
Button but;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
/**
* 实例网络框架Retrofit:
* 1.将下载的Json转为Java对象
* 2.基层http网址
* 3.构建build
*/
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://www.qubaobei.com/ios/cf/")
.build();
//实例接口MenuService:
MenuService menuService = retrofit.create(MenuService.class);
//获取到接口,再获取到其getResult方法:
Call<JavaBean> resualt = menuService.getResualt();
//拿到方法,通过异步操作,
resualt.enqueue(new Callback<JavaBean>() {
@Override
public void onResponse(Call<JavaBean> call, Response<JavaBean> response) {
Toast.makeText(MainActivity.this, "加载成功!", Toast.LENGTH_SHORT).show();
JavaBean body = response.body();
List<JavaBean.DataBean> data = body.getData();
Log.i("sadsad",data.toString());
//recycleView展示模式:
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
rv.setLayoutManager(linearLayoutManager);
//recycleView适配器:
MyRecycleAdapter myRecycleAdapter = new MyRecycleAdapter(MainActivity.this, data);
rv.setAdapter(myRecycleAdapter);
}
@Override
public void onFailure(Call<JavaBean> call, Throwable t) {
Toast.makeText(MainActivity.this, "加载失败!", Toast.LENGTH_SHORT).show();
}
});
}
}
效果如下: