在 Android 中使用 Retrofit 2.0

Using Retrofit 2.0 in Android

由于我对像 Retrofit 这样的 Android 使用第三方 HTTP 库还很陌生,所以有几个问题想请教各位大神。

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

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

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. 上面泛型中的Repo是什么意思?这是我仍然无法弄清楚的第一件事。

  2. @POST 或@GET 等注解后面的括号里应该写什么?是服务器URL下的子目录的意思吗?根据上面的示例代码,@GET 注释是否声明 listRepos 方法从 'user' 路径或其他什么地方获取用户值?这太令人困惑了..

拜托,我对这个世界真的很陌生,所以我非常需要你的帮助。提前致谢。

    本例中的
  1. 'Repo' 表示 Github 上的存储库。 Retrofit 自动反序列化 JSON 对 Java POJO 的响应。该示例从 Github API 中获取有关 Github 存储库的信息,获取的存储库信息由 Repo class / Repo 对象列表表示。您必须提供自己的 class 表示您从服务器获取的数据/API。
  2. Does it mean a subdirectory under the server URL?

基本上,是的。它是您尝试在 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。

.

正常工作

包裹 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

添加这个库

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

public 接口 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);

    }
}

}

第 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 步实用程序 class

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;
    }
}

第三步界面

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步豆子class

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);
            }
        }
}