可以使用Retrofit Library的支持
首先,在你的 gradle 中,添加这一行来下载。
compile 'com.squareup.retrofit2:retrofit:2.4.0'
其次,在@Body中选择RequestBody的类型
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
然后将其添加到您的 gradle 中:
compile 'com.squareup.retrofit2:converter-gson:2.4.0'
第三,创建一个接口类以使用@GET方法或其他方法,例如:
public interface CallMethodService {
@GET("search")
Call<ResponseModel> getResponseModel();
}
最后,在您的 MainActivity 中:
创建一个改造
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("base server link")
.addConverterFactory(RequestBody type)
.build();
例如:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.giphy.com/v1/gifs/")
.addConverterFactory(GsonConverterFactory.create())
.build();
然后调用获取数据:
retrofit.create(CallMethodService.class).getResponseModel()
.enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
//get data
}
@Override
public void onFailure(Call<GifResponse> call, Throwable t) {
// No internet
}
});