Retrofit2.0的get post请求简单数据

首先导入依赖

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
新建工程,创建Api的class类

public class Api {
//http://v.juhe.cn/------这个在Api里面声明
// toutiao/index?type=shehui&key=6535f9a621cb3661b96f538ea740c9b6------这个在接口里面声明
public static final String BASE_URL = "http://v.juhe.cn/";

}
创建一个接口
public interface InterfaceApi {
    // toutiao/index?type=shehui&key=6535f9a621cb3661b96f538ea740c9b6------这个在接口里面声明

    @GET("toutiao/index?type=shehui&key=6535f9a621cb3661b96f538ea740c9b6")
//UserBean是自己创建bean类的名称,没有其他意思
 Call<UserBean> getData();//getData()名字可以随便改!

//添加条件的get
@GET("user/getUserInfo")

Call<Bean> getData(@Query("uid") int uid);

//post请求---getpost是方法名,不要忘记在MainActivity类里面改
@FormUrlEncoded
@POST("user/getUserInfo")
Call<Bean> getPost(@Field("uid") int uid);

 }
在MainActivity类里面声明
private InterfaceApi interfaceApi;
private Retrofit retrofit;
private Call<UserBean> context;
在onCreate()方法里面写
retrofit = new Retrofit.Builder().baseUrl(Api.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
//创建接口类
interfaceApi = retrofit.create(InterfaceApi.class);
context = interfaceApi.getData();

context.enqueue(new Callback<UserBean>() {
    @Override
    public void onResponse(Call<UserBean> call, Response<UserBean> response) {
        if (response != null && response.isSuccessful() && response.body() != null) {
            try {
                UserBean string = response.body();
                List<UserBean.ResultBean.DataBean> data = string.getResult().getData();
                System.out.println("请求的data的长度 = " + data.size());

                for (int i = 0; i < data.size(); i++) {
                    System.out.println("标题是 = " + data.get(i).getTitle());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

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

    }
});

这个方法是onCreate()外面的
@Override
protected void onDestroy() {
    super.onDestroy();
    context.cancel();
}

参考的是另一篇博客,写的很详细
http://blog.csdn.net/android_study_ok/article/details/51480382

猜你喜欢

转载自blog.csdn.net/color_0716/article/details/78394272
今日推荐