导入依赖
// 网络请求
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
manifests里面的明文配置
android:networkSecurityConfig="@xml/nettools"
网络明文
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<!--禁用掉明文流量请求的检查-->
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
请求数据
[{"id":"1","name":"小红","version":"21"},
{"id":"2","name":"小丽","version":"32"},
{"id":"2","name":"王刚","version":"41"}]
根据数据编写数据类
public class App {
private String id;
private String name;
private String version;
// 省略get(), set(), toString()
}
Service接口
public interface AppService {
@GET("get_data.json")
Call<List<App>> getAppData();
}
retrofit的简单实现
public class MainActivity extends AppCompatActivity {
private static final String TAG = "网络请求";
private static final String BASE_URL = "http://10.0.2.2/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofitRequest(BASE_URL);
}
private AppService getAppService(String url) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(AppService.class);
}
private void retrofitRequest(String url) {
getAppService(url).getAppData().enqueue(new retrofit2.Callback<List<App>>() {
@Override
public void onResponse(retrofit2.Call<List<App>> call, retrofit2.Response<List<App>> response) {
List<App> list = response.body();
for (App app : list) {
Log.e(TAG, "onResponse: " + app + "\n");
}
}
@Override
public void onFailure(retrofit2.Call<List<App>> call, Throwable t) {
t.printStackTrace();
}
});
}
}