在Android中使用Retrofit 2.0

时间:2015-09-24 21:14:07

标签: android retrofit

由于我对使用第三方HTTP库(如Retrofit)非常陌生,我想问一些可以帮助我的问题。

最近从Retrofit 1.9到2.0的过渡似乎发生了很大的变化,例如API的变化。因此,即使在自己的网页上,也找不到使用该库的正确文档。

当涉及到在服务器上实现注册用户的HTTP请求时,根据网页,似乎首先要创建一个定义角色的接口(例如POST,GET等)。例如:

public interface GitHubService {
  @GET("/users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

似乎我应该创建一个Retrofit实例来连接服务器并使用

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

我真正想知道的是,

  1. 上述仿制药中的回购是什么意思?这是我仍然无法弄清楚的第一件事。

  2. 在括号中应该写什么,然后是@POST或@GET等每个注释?它是否意味着服务器URL下的子目录?根据上面的示例代码,@ Get注释表明listRepos方法是否从“用户”路径获取用户值?这太令人困惑了..

  3. 拜托,我对这个世界真的很陌生,所以我非常渴望得到你的帮助。提前谢谢。

4 个答案:

答案 0 :(得分:4)

  1. 此示例中的“Repo”表示Github上的存储库。 Retrofit会自动将JSON响应反序列化为Java POJO。该示例从Github API获取有关Github存储库的信息,获取的存储库信息由Repo类/ Repo对象列表表示。您必须提供自己的类表示,表示您从服务器/ API获取的数据。
  2.   

    是否意味着服务器URL下的子目录?

  3. 基本上,是的。它是您尝试在baseUrl指定的服务器上访问的资源的路径/ Uri。

    在这种情况下,我们有baseUrl https://api.github.com。我们追加路径/users/{user}/repos。方法

    @GET("/users/{user}/repos")
          Call<List<Repo>> listRepos(@Path("user") String user);
    

    将用户id作为参数,并用该参数替换{user}

    因此,如果使用参数JakeWharton调用该方法,则完整的Uri是

    https://api.github.com/users/JakeWharton/repos
    

    您可以从浏览器中调用它来查看响应。 您必须更改这些Url / Uri字符串以匹配您要访问的API。

答案 1 :(得分:0)

正在运作

enter image description here     package com.keshav.gmailretrofitexampleworking.network;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://api.androidhive.info/json/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
==============================================
package com.keshav.gmailretrofitexampleworking.network;

import com.keshav.gmailretrofitexampleworking.models.Message;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {
    @GET("inbox.json")
    Call<List<Message>> getInbox();
}

=============================================

致电APi

private void getInbox() {
    swipeRefreshLayout.setRefreshing(true);

    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<List<Message>> call = apiService.getInbox();
    call.enqueue(new Callback<List<Message>>() {
        @Override
        public void onResponse(Call<List<Message>> call, Response<List<Message>> response) {
            // clear the inbox
            messages.clear();

            // add all the messages
            // messages.addAll(response.body());

            // TODO - avoid looping
            // the loop was performed to add colors to each message

            Log.e("keshav","response" +response.body());

            for (Message message : response.body()) {
                // generate a random color

                // TODO keshav Generate Random Color Here
                message.setColor(getRandomMaterialColor("400"));
                messages.add(message);
            }

            mAdapter.notifyDataSetChanged();
            swipeRefreshLayout.setRefreshing(false);
        }

        @Override
        public void onFailure(Call<List<Message>> call, Throwable t) {
            Toast.makeText(getApplicationContext(), "Unable to fetch json: " + t.getMessage(), Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
        }
    });
}

编译'com.google.code.gson:gson:2.6.2'

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

compile 'com.squareup.retrofit2:converter-gson:2.0.2'

源代码

https://drive.google.com/open?id=0BzBKpZ4nzNzUVFRnVVkzc0JabUU

https://drive.google.com/open?id=0BzBKpZ4nzNzUc2FBdW00WkRfWW8

答案 2 :(得分:0)

添加此库

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

RetrofitClient.java

public class RetroClient {

private static final String ROOT_URL = "xyz";
private static Retrofit getRetrofitInstance() {
    return new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}
public static ApiService getApiService() {
    return getRetrofitInstance().create(ApiService.class);
}

}

ApiInterface.java

公共接口ApiService {

@GET("get_exams.php")
Call<GetExamListResponse> getExamList();

@FormUrlEncoded
@POST("get_exam_details.php")
Call<GetExamListDetailResponse> getExamDetail(@Field("exam_id") String exam_id);

Response.java

@SerializedName("data")
@Expose
private ArrayList<GetCountryListModel> getCountryListModel = null;

Activity.java

 public void get_alluni() {
    ApiService api = RetroClient.getApiService();
    Call<GetAllUniversityListResponse> call = api.getAllUniversitiesList();
    call.enqueue(new Callback<GetAllUniversityListResponse>() {
        @Override
        public void onResponse(Call<GetAllUniversityListResponse> call, Response<GetAllUniversityListResponse> response) {

            if (response.isSuccessful()) {
                getAllUniversitiesModels = response.body().getGetAllUniversitiesModels();
                Log.e("EMPASASAS", getAllUniversitiesModels.toString());

                LinearLayoutManager linearLayout = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false);
                recyclerView1 = (RecyclerView) findViewById(R.id.recycler_view_mostpopularcoursemain);
                recyclerView1.setVisibility(View.VISIBLE);
                //recyclerView.setVisibility(View.GONE);
                recyclerView1.setLayoutManager(linearLayout);
                eAdapter1 = new AllUniversityRecyclerAdapter(MainActivity.this, getAllUniversitiesModels);
                recyclerView1.setAdapter(eAdapter1);
            }
        }

        @Override
        public void onFailure(Call<GetAllUniversityListResponse> call, Throwable t) {
            //Toast.makeText(MainActivity.this, "Fail", Toast.LENGTH_SHORT).show();

        }
    });
}

Adapter.java

public class ChooseExamRecyclerViewAdapter extends RecyclerView.Adapter<ChooseExamRecyclerViewAdapter.CustomViewHolder> {
private ArrayList<GetExamListModel> getExamListModels;
Context context;

public ChooseExamRecyclerViewAdapter(Context context, ArrayList<GetExamListModel> getExamListModels) {
    this.getExamListModels = getExamListModels;
    this.context = context;
}

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.choose_exam_list, parent, false);

    return new CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
    GetExamListModel getExamListModel = getExamListModels.get(position);
    holder.exam_name.setText(getExamListModel.getExam_name());
    holder.field_name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Context context = v.getContext();
            Intent intent = new Intent(context, ExamDetailsActivity.class);
            intent.putExtra("EXAMID", getExamListModel.getExam_id());
            context.startActivity(intent);
        }
    });
}

@Override
public int getItemCount() {
    return getExamListModels.size();
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    public TextView exam_name;
    public CardView field_name;

    public CustomViewHolder(View view) {
        super(view);
        exam_name = (TextView) view.findViewById(R.id.exam_name);
        field_name = (CardView) view.findViewById(R.id.field_name);

    }
}

}

答案 3 :(得分:0)

第1步依赖性:

  //RETROFIT
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation "com.squareup.okhttp3:okhttp:4.7.2"
    implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'

第2步实用程序类

public class Utils {
    private static Utils singleton;
    public Dialog dialog;

    public static Utils getInstance() {
        if (singleton == null) {
            singleton = new Utils();
        }
        return singleton;
    }

    public ApiInterfaces initializeWebServiceCall(Context context) {
        Gson gson = new GsonBuilder().setLenient().create();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.MINUTES).readTimeout(1, TimeUnit.MINUTES).addInterceptor(interceptor).build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiEndPoint.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        ApiInterfaces mRestAPI = retrofit.create(ApiInterfaces.class);
        return mRestAPI;
    }
}

第3步界面

public interface ApiInterfaces {

 @FormUrlEncoded
    @POST(ApiEndPoint.BASE_URL + "address_list")
    Call<AddressBean> address_list(@Field("user_id") String user_id);
}

第4步api调用

 private RecyclerView rec_address;
    private ArrayList<AddressBean.AddressData> AddressList = new ArrayList();





    Call<AddressBean> call = Utils.getInstance().initializeWebServiceCall(SelectAddressActivity.this).address_list(id);
        call.enqueue(new Callback<AddressBean>() {
            @Override
            public void onResponse(Call<AddressBean> call, Response<AddressBean> response) {
                if (response.body() != null) {
                    if (!SelectAddressActivity.this.isFinishing() && pd.isShowing())
                        pd.dismiss();
                    String status, message, id, pincode, house_no, city, area, state, user_id, name, mobile_no, alt_mobile_no;
                    String address;
                    status = response.body().getStatus();
                    message = response.body().getMessage();
                    Log.d("response12", "SUCCESS:" + status + "\n MESSAGE:" + message);
                    if (response.body().getStatus().equalsIgnoreCase("success")) {
                        pd.dismiss();
//                        Toast.makeText(AddAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                        ArrayList<AddressBean.AddressData> list = response.body().getDataList();
                        Log.d("fugweut325ncv", list.toString() + "\n " + list.size());
                        for (int i = 0; i < list.size(); i++) {
                            id = list.get(i).getId();
                            pincode = list.get(i).getPincode();
                            house_no = list.get(i).getHouse_no();
                            city = list.get(i).getCity();
                            area = list.get(i).getArea();
                            state = list.get(i).getState();
                            name = list.get(i).getName();
                            mobile_no = list.get(i).getMobile_no();
                            alt_mobile_no = list.get(i).getAlt_mobile_no();
                            AddressBean.AddressData adata = new AddressBean.AddressData(id, pincode, house_no, city, area, state, name, mobile_no, alt_mobile_no);
                            AddressList.add(adata);
                            Log.d("dutgwihv", "PINCODE" + pincode + "\n HOUSE NO:" + house_no + "CITY:" +
                                    city + "\n AREA" + area + "\n STATE" + state + "\n name:" + name + "\n mobile:"
                                    + mobile_no + "alternate:" + alt_mobile_no);
                            if (alt_mobile_no.equals("0")) {
                                address = "Name:" + name + "\nMobile Number:" + mobile_no + "\nAddress:" + house_no + ", " + area + ", " + city + ", " + state + "- " + pincode;
                            } else {
                                address = " Name:" + name + "\n Mobile Number:" + mobile_no + "," + alt_mobile_no + "\n Address:" + house_no + ", " + area + ", " + city + ", " + state + "- " + pincode;
                            }
                        }
                        AddressAdapter adapter = new AddressAdapter(SelectAddressActivity.this, AddressList);
                        rec_address.setLayoutManager(new GridLayoutManager(SelectAddressActivity.this, 1));
                        rec_address.setItemAnimator(new DefaultItemAnimator());
                        rec_address.setAdapter(adapter);
                    } else {
                        pd.dismiss();
                        Toast.makeText(SelectAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    if (!SelectAddressActivity.this.isFinishing() && pd.isShowing()) {
                        pd.dismiss();
                        Toast.makeText(SelectAddressActivity.this, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<AddressBean> call, Throwable t) {
                if (!SelectAddressActivity.this.isFinishing() && pd.isShowing())
                    pd.dismiss();
                AlertDialog.Builder b1 = ApiEndPoint.getAlertDialog(SelectAddressActivity.this, "Time Out", ApiEndPoint.getMessage(), R.mipmap.ic_launcher, "Cancel");
                b1.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        sendAddressListRequest();
                    }
                });
                b1.create().show();
            }
        });

第5步Bean类

public class AddressBean implements Parcelable{
    @SerializedName("status")
    @Expose
    private String status;

    @SerializedName("message")
    @Expose
    private String message;

    @SerializedName("data")
    @Expose
    private ArrayList<AddressData> DataList;

    protected AddressBean(Parcel in) {
        status = in.readString();
        message = in.readString();
        DataList = in.createTypedArrayList(AddressData.CREATOR);
    }

    public static final Creator<AddressBean> CREATOR = new Creator<AddressBean>() {
        @Override
        public AddressBean createFromParcel(Parcel in) {
            return new AddressBean(in);
        }

        @Override
        public AddressBean[] newArray(int size) {
            return new AddressBean[size];
        }
    };

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public ArrayList<AddressData> getDataList() {
        return DataList;
    }

    public void setDataList(ArrayList<AddressData> dataList) {
        DataList = dataList;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(status);
        parcel.writeString(message);
        parcel.writeTypedList(DataList);
    }

    public static class AddressData implements Parcelable {

            public AddressData() {
            }

            public AddressData(String id, String pincode, String house_no, String city, String area, String state, String name, String mobile_no, String alt_mobile_no) {
                this.id = id;
                this.pincode = pincode;
                this.house_no = house_no;
                this.city = city;
                this.area = area;
                this.state = state;
                this.name = name;
                this.mobile_no = mobile_no;
                this.alt_mobile_no = alt_mobile_no;
            }

            @SerializedName("id")
        @Expose
        private String id;

        @SerializedName("pincode")
        @Expose
        private String pincode;

        @SerializedName("house_no")
        @Expose
        private String house_no;

        @SerializedName("city")
        @Expose
        private String city;

        @SerializedName("area")
        @Expose
        private String area;

        @SerializedName("state")
        @Expose
        private String state;

        @SerializedName("name")
        @Expose
        private String name;

        @SerializedName("mobile_no")
        @Expose
        private String mobile_no;

        @SerializedName("alt_mobile_no")
        @Expose
        private String alt_mobile_no;

            protected AddressData(Parcel in) {
                id = in.readString();
                pincode = in.readString();
                house_no = in.readString();
                city = in.readString();
                area = in.readString();
                state = in.readString();
                name = in.readString();
                mobile_no = in.readString();
                alt_mobile_no = in.readString();
            }

            public static final Creator<AddressData> CREATOR = new Creator<AddressData>() {
                @Override
                public AddressData createFromParcel(Parcel in) {
                    return new AddressData(in);
                }

                @Override
                public AddressData[] newArray(int size) {
                    return new AddressData[size];
                }
            };

            public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getPincode() {
            return pincode;
        }

        public void setPincode(String pincode) {
            this.pincode = pincode;
        }

        public String getHouse_no() {
            return house_no;
        }

        public void setHouse_no(String house_no) {
            this.house_no = house_no;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getArea() {
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }

        public String getState() {
            return state;
        }

        public void setState(String state) {
            this.state = state;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMobile_no() {
            return mobile_no;
        }

        public void setMobile_no(String mobile_no) {
            this.mobile_no = mobile_no;
        }

        public String getAlt_mobile_no() {
            return alt_mobile_no;
        }

        public void setAlt_mobile_no(String alt_mobile_no) {
            this.alt_mobile_no = alt_mobile_no;
        }

            @Override
            public int describeContents() {
                return 0;
            }

            @Override
            public void writeToParcel(Parcel parcel, int i) {
                parcel.writeString(id);
                parcel.writeString(pincode);
                parcel.writeString(house_no);
                parcel.writeString(city);
                parcel.writeString(area);
                parcel.writeString(state);
                parcel.writeString(name);
                parcel.writeString(mobile_no);
                parcel.writeString(alt_mobile_no);
            }
        }
}