android retrofit入门,Android Retrofit 入门教程

首先添加依赖

compile 'com.squareup.retrofit2:retrofit:2.3.0'

compile 'com.squareup.retrofit2:converter-gson:2.3.0'//请求结果直接转化为实体类,省略gson转化

创建一个接口

// 完整地址: http://www.wuhaojun.com/api/android/customer?type=1

public interface CustomerService {

@GET("/api/android/customer")//Get请求地址

Call getCustomer(@Query("type") int type);//定义参数type的当前是第几页 1,2,3 ...

}

请求方法

String baseUrl = "http://www.wuhaojun.com/";//请求地址,固定的一部分

Retrofit retrofit = new Retrofit.Builder()

.baseUrl(baseUrl)

.addConverterFactory(GsonConverterFactory.create())//请求结果直接转化实体类

.build();

CustomerService movieService = retrofit.create(CustomerService.class);//创建对象

Call call = movieService.getCustomer(1);//传递请求参数 对应接口中的定义

call.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

Log.i(TAG, "onResponse: "+response.body().getMessage());//返回的就是实体类,不需要Gson转换

}

@Override

public void onFailure(Call call, Throwable t) {

Log.i(TAG, "onFailure: "+t.getMessage());

}

});

最后,别忘了添加网络权限

附加其他上传类型

//post json

@POST

Call reJson(@Url String url, @Body RequestBody body);

HashMap params = new HashMap<>();

params.put("phone_num", "123");

JSONObject json = new JSONObject(params);

RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=utf-8"), json);//转化类型

//post params

@POST

@FormUrlEncoded

Call reParams(@Url String url, @FieldMap Map map);

HashMap hashMap = new HashMap<>();

hashMap.put("user", "test");

//post file map

@POST

@Multipart

Call reUploadFile(@Url String url, @PartMap Map params);

File file = new File("");

Map hashMap = new HashMap<>();

hashMap.put("json", RequestBody.create(MediaType.parse("text/plain"), "jsonargs"));//键值对

hashMap.put("file\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));//文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值