您的位置:首页 > 理论基础 > 计算机网络

Retrofit的GET请求使用,结合Gson解析

2017-03-05 17:07 453 查看

添加依赖

compile 'com.squareup.retrofit2:retrofit:2.2.0'
//转换器
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.google.code.gson:gson:2.8.0'


编写API

public interface Api {

@GET("Guolei1130")
Call<gitBean> getURl();

//多参数示列
//http://www.xxxx.com/action/api/xxxx?pageIndex=0&catalog=1&pageSize=20
//@GET("xxxx")
//Call<String> newslist(@Query("pageIndex") int pageIndex, @Query("catalog") int catalog, @Query("pageSize") int pageSize);
}


添加常量类Constant 和 Bean类

public class Constant {

public static final String BASE_URL = "https://api.github.com/users/";
}

//bean类使用GsonFormat自动生成的
public class GitBean {

public String login;
public int id;
public String avatar_url;
public String gravatar_id;
public String url;
public String html_url;
public String followers_url;
public String following_url;
public String gists_url;
public String starred_url;
public String subscriptions_url;
public String organizations_url;
public String repos_url;
public String events_url;
public String received_events_url;
public String type;
public boolean site_admin;
public String name;
public Object company;
public String blog;
public String location;
public String email;
public Object hireable;
public String bio;
public int public_repos;
public int public_gists;
public int followers;
public int following;
public String created_at;
public String updated_at;
}


封装网络请求

封装网络请求,方便调用,这里只做了Retrofit的构建,和gson的解析(有需要本地缓存的也可以添加在此类)
public class MyRetrofit {

private static MyRetrofit sMyRetrofit;

private final Api mApi;

private Gson mGson = new GsonBuilder().setLenient().create();//设置宽大处理畸形的json

//构建Retrofit
private MyRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)//访问的url
.addConverterFactory(GsonConverterFactory.create(mGson))//添加转换器
.build();
mApi = retrofit.create(Api.class);//创建接口
}

//单例
public static MyRetrofit getInstance() {
if (sMyRetrofit == null) {
synchronized (MyRetrofit.class) {
if (sMyRetrofit == null) {
sMyRetrofit = new MyRetrofit();
}
}
}
return sMyRetrofit;
}

public Api getApi() {
return mApi;
}

}


发起请求

public class RetrofitAvticity extends AppCompatActivity{

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Call<GitBean> uRl = MyRetrofit.getInstance().getApi().getURl();
uRl.enqueue(new Callback<GitBean>() {
@Override
public void onResponse(Call<GitBean> call, Response<GitBean> response) {
//请求成功
GitBean bean = response.body();
Toast.makeText(getApplicationContext(), bean.name, Toast.LENGTH_SHORT).show();
}

@Override
public void onFailure(Call<GitBean> call, Throwable t) {
Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
}
});
}
}


总结

封装了Retrofit的请求,后期使用很方便,只要在api中添加一行代码就可以实现不同的请求,很大的提高了扩展性.(后面更新post请求)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Retrofit gson 网络请求