注:使用之前先依赖retrofit(
compile
'com.squareup.retrofit2:retrofit:2.1.0'
compile
'com.squareup.retrofit2:converter-gson:2.1.0'),
定义好接口后,先进行初始化,以下是代码,所有请求的方法最好写在一个接口中
retrofit
=
new
Retrofit.Builder().
baseUrl(
"http://www.yxtintin.com:8280/"
).
//这一行的作用是,可以将resPonse返回的结果直接转化为对象的形式,必须依赖以上的第二个库
addConverterFactory(GsonConverterFactory.
create
()).
build();
myInterface
=
retrofit
.create(MyInterface.
class
);
一:get请求
①
接口的写法:
@GET
(
"wx/getphone"
) 最常见的一种写法,通过query来注解参数
Call<Result> getNumberByGet(
@Query
(
"deviceid"
) String deviceId,
@Query
(
"iccid"
) String iccid);
调用的写法:
myInterface
.getNumberByGet(
"00000"
,
"89860616010021146681"
).enqueue(
new
Callback<Result>()
②
接口的写法
,通过占位符的形式将参数列出,@path注解的是形参
@GET
(
"wx/getphone/{deviceid}{iccid}"
)
Call<Result> getNumberByPath(
@Path
(
"deviceid"
) String deviceid,
@Path
(
"iccid"
) String iccid);
调用的写法:
myInterface
.getNumberByPath(
"00000"
,
"89860616010021146681"
).enqueue(
new
Callback<Result>() {}
③
接口的写法:将参数放进一个map集合中
@GET
(
"wx/getphone"
)
Call<Result> getMap(
@QueryMap
HashMap<String, String> map);
调用的写法:
HashMap<String, String> map =
new
HashMap<>();
map.put(
"deviceid"
,
"00000"
);
map.put(
"iccid"
,
"89860616010021146681"
);
myInterface
.getMap(map).enqueue(
new
Callback<Result>() {}
二:post请求:(1是上传json,2,3是上传表单)
①
接口的写法:(上传的是json)
@POST
(
"wx/getphone"
)
Call<Result> postobject(
@Body
Result result);
调用的写法:
myInterface
.postobject(
new
Result(
"1"
,
"2"
)).enqueue(
new
Callback<Result>() {}
②
接口的写法:(表单,通过map集合的形式上传)
@FormUrlEncoded
@POST
(
"wx/getphone"
)
Call<Result> postmap(
@FieldMap
HashMap<String, String> map);
调用的写法:
HashMap<String, String> map =
new
HashMap<>();
map.put(
"deviceid"
,
"00000"
);
map.put(
"iccid"
,
"89860616010021146681"
);
myInterface
.postmap(map).enqueue(
new
Callback<Result>() {.....}
③
接口的写法:(表单,类似于get请求的query
)
@FormUrlEncoded
@POST
(
"wx/getphone"
)
Call<Result> postForm(
@Field
(
"deviceid"
) String deviceid,
@Field
(
"iccid"
) String fild);
调用的写法:
myInterface
.postForm(
"00000"
,
"89860616010021146681"
).enqueue(
new
Callback<Result>() {...}