了解Retrofit的使用
1.添加依赖,因为Retrofit是基于okhttp的:
// Okhttp库
compile 'com.squareup.okhttp3:okhttp:3.1.2'
// Retrofit库
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'//解析使用的Gson
2.网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
3.创建返回数据对象,如:
package ipos.crg.com.recycledemo;
/**
* Description:
* Date : 2018/7/31 17:47
*/
public class ResponseInfo {
private String error;
private String result;
private String msgToken;
public ResponseInfo() {
}
public ResponseInfo(String error, String result, String msgToken) {
this.error = error;
this.result = result;
this.msgToken = msgToken;
}
public String getError() {
return error == null ? "" : error;
}
public void setError(String error) {
this.error = error;
}
public String getMsgToken() {
return msgToken == null ? "" : msgToken;
}
public void setMsgToken(String msgToken) {
this.msgToken = msgToken;
}
public String getResult() {
return result == null ? "" : result;
}
public void setResult(String result) {
this.result = result;
}
@Override
public String toString() {
return "ResponseInfo{" +
"error='" + error + '\'' +
", result='" + result + '\'' +
", msgToken='" + msgToken + '\'' +
'}';
}
}
4.创建接口类,如;
public interface ResponseApi {
@GET("myday05/{method}")
Call<ResponseInfo> getResponse(@Path("method") String method);
}
或者
public interface ResponseApi {
@GET("myday05/a.json")
Call<ResponseInfo> getResponse();
}
通过这俩个代码可以看出@path的用法,这个接口主要就是直接可以通过注释请求;
@Header
@Path(与get后面的{}里面的值对应)
@Body
@GET
@POST(get,post,值不能为空)
@Query("num") String num(请求接口时,传入的数据)
5.实现网络请求
Retrofit retrofit =
new Retrofit.Builder()
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())//设置数据解析器
.baseUrl("http://192.168.0.190:8989/")//最好带/,网络请求地址
.build();
ResponseApi responseApi = retrofit.create(ResponseApi.class);
response = responseApi.getResponse("a.json");
response.enqueue(new Callback<ResponseInfo>() {
@Override
public void onResponse(Call<ResponseInfo> call, Response<ResponseInfo> response) {
Log.e("www", "ResponseInfo = " + response.body().toString());
}
@Override
public void onFailure(Call<ResponseInfo> call, Throwable t) {
Log.e("www", "Throwable = " + t.getMessage());
}
});
网友评论