您的位置:首页 > 其它

Retrofit简单使用方法

2018-02-08 14:40 344 查看
废话不多说了,直接说步骤,后续使用方法会继续更新。

1.配置gradle

在grald中添加

compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2' //解析数据使用

2.创建获取数据entity

public class User {
private String name;
private String email;
private String id;

后面get/set方法省略

3.添加权限 

<uses-permission android:name="android.permission.INTERNET"
/>
4.编写获取数据接口

public interface HttpInfo {
@GET("user/info")
Call<User> getUserInfo(@Query("id") int id);//retrofit建议url不用/开头
}

5.获取数据


public void getUserInfo(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.138.01:8080/")
.addConverterFactory(GsonConverterFactory.create())
.build();
HttpInterface service = retrofit.create(HttpInterface.class);
Call<User> call = service.getUserInfo(1);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User mUser= response.body();
//Todo 获取到user信息,后续操作在这里进行
}

@Override
public void onFailure(Call<User> call, Throwable t) {

}
});
}

retrofit 的github地址:https://github.com/square/retrofit
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: