Retrofit2极简教程

注:使用之前先依赖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>() {...}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值