Android Retrofit 简单使用 [英] Android Retrofit simple usage

查看:31
本文介绍了Android Retrofit 简单使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次尝试使用 Android Retrofit,我正在学习教程并陷入第一步...1.使用Gson2.3、okhttp2.1.0、okhttp-urlconnection2.1.0、retrofit-1.8.02. 我的网络服务在 .php 脚本中并返回这种数据 {"idInfo":"12","typeInfo":"2"}3.我创建了模型类gitmodel

公共类 gitmodel {公共 gitmodel(int idInfo, int typeInfo) {this.idInfo = idInfo;this.typeInfo = typeInfo;}私人 int idInfo;私有整数类型信息;公共 gitmodel() {}公共 int getIdInfo() {返回idInfo;}公共无效 setIdInfo(int idInfo) {this.idInfo = idInfo;}公共 int getTypeInfo() {返回类型信息;}public void setTypeInfo(int typeInfo) {this.typeInfo = typeInfo;}}

"4.我创建了如下所示的接口类 gitapi

公共接口gitapi {@GET("/users/{user}")public void getFeed(@Path("user") String user,Callback response);}

我在此类中收到错误无法解析路径"并且无法解析 gitmodel.我知道这只是一个开始,但我不能继续.

解决方案

尝试以下步骤:

  1. 添加 gradle 并同步您的项目

<块引用>

实现'com.squareup.retrofit2:retrofit:2.0.2'

实现'com.squareup.retrofit2:converter-gson:2.0.2'

  1. 创建您的 pojo 类并像这样添加模型类

     公共类 LoginModel {@SerializedName("代码")@暴露私人字符串代码;@SerializedName("消息")@暴露私人字符串消息;@SerializedName("数据")@暴露私人数据数据;公共字符串 getCode() {返回码;}公共无效集代码(字符串代码){this.code = 代码;}公共字符串 getMessage() {回消息;}公共无效setMessage(字符串消息){this.message = 消息;}公共数据 getData() {返回数据;}公共无效集数据(数据数据){this.data = 数据;}公共类数据{@SerializedName("id")@暴露私人字符串ID;@SerializedName("facebookId")@暴露私人字符串facebookId;@SerializedName("密码")@暴露私人字符串密码;@SerializedName("securityHash")@暴露私有字符串 securityHash;@SerializedName("用户名")@暴露私人字符串用户名;@SerializedName("firstName")@暴露私人字符串名字;@SerializedName("lastName")@暴露私人字符串姓氏;@SerializedName("email")@暴露私人字符串电子邮件;@SerializedName("联系人")@暴露私人字符串联系人;@SerializedName("userLastLoggedIn")@暴露私人字符串 userLastLoggedIn;@SerializedName("状态")@暴露私有字符串状态;@SerializedName("createdAt")@暴露私人字符串 createdAt;@SerializedName("updatedAt")@暴露私人字符串updatedAt;@SerializedName("profileStatus")@暴露私人字符串配置文件状态;@SerializedName("性别")@暴露私人字符串性别;公共字符串 getId() {返回标识;}公共无效setId(字符串ID){this.id = id;}公共字符串 getFacebookId() {返回facebookId;}公共无效setFacebookId(字符串facebookId){this.facebookId = facebookId;}公共字符串 getPassword() {返回密码;}public void setPassword(字符串密码){this.password = 密码;}公共字符串 getSecurityHash() {返回 securityHash;}public void setSecurityHash(String securityHash) {this.securityHash = securityHash;}公共字符串 getUserName() {返回用户名;}public void setUserName(String userName) {this.userName = 用户名;}公共字符串 getFirstName() {返回名字;}public void setFirstName(String firstName) {this.firstName = firstName;}公共字符串 getLastName() {返回姓氏;}public void setLastName(String lastName) {this.lastName = 姓氏;}公共字符串 getEmail() {回邮件;}公共无效setEmail(字符串电子邮件){this.email = 电子邮件;}公共字符串 getContact() {返回联系方式;}public void setContact(String contact) {this.contact = 联系人;}公共字符串 getUserLastLoggedIn() {返回用户上次登录;}public void setUserLastLoggedIn(String userLastLoggedIn) {this.userLastLoggedIn = userLastLoggedIn;}公共字符串 getStatus() {返回状态;}公共无效 setStatus(字符串状态){this.status = 状态;}公共字符串 getCreatedAt() {返回 createdAt;}public void setCreatedAt(String createdAt) {this.createdAt = createdAt;}公共字符串 getUpdatedAt() {返回更新于;}public void setUpdatedAt(String updatedAt) {this.updatedAt = updatedAt;}公共字符串 getProfileStatus() {返回个人资料状态;}public void setProfileStatus(String profileStatus) {this.profileStatus = profileStatus;}公共字符串 getGender() {回归性别;}公共无效setGender(字符串性别){this.gender = 性别;}}}

  2. 在你的包中添加三个类

<块引用>

  • RetrofitApi 接口
  • 改造客户端
  • 改造内容

1.1 像这样添加 RetrofitApiInterface Calss:

<小时>

 公共接口 RetrofitApiInterface {/*登录API发布方法*/@POST("登录")@FormUrlEncoded调用<登录模型>loginMethod(@Field("email") String email, @Field("password") String password);}

1.2 添加 RetrofitClient 类

<小时>

公共类 RetrofitClient {私有静态改造改造= null;公共静态改造 getClient(String url){如果(改造==空){改造 = 新改造.Builder().baseUrl(网址).addConverterFactory(GsonConverterFactory.create()).建造();}返回改造;}}

1.3 添加 RetrofitConstent 类

<小时>

公共类 RetrofitConstent {公共静态字符串 BASE_URL="";公共静态 RetrofitApiInterface retrofitApiInterface(){返回 RetrofitClient.getClient(BASE_URL).create(RetrofitApiInterface.class);}}

4.添加像这样s

的Retrofit api方法<小时>

/*简单的登录API方法*/public void loginAPIMethod(String email, String password) {dialog = new Dialog(this, android.R.style.Theme_Translucent);dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);dialog.setContentView(R.layout.custom_progress_dialog);dialog.setCancelable(false);对话框显示();调用<登录模型>呼叫 = 空;尝试 {call = YabbyConstant.retrofitApiInterface().loginMethod(email, password);call.enqueue(new Callback() {@覆盖public void onResponse(Call call, Response response) {/*获取成功响应*/Log.e(TAG + "Response", "" + response.body().getCode());尝试 {if (response.body().getCode().equalsIgnoreCase("1")) {dialog.dismiss();LoginModel.Data 数据 = response.body().getData();/*将数据保存到共享首选项中*/Preference.storeUserPreferences(SignInActivity.this, ApiUtils.USER, new Gson().toJson(response.body().getData()));Log.e(TAG, "sharedLogin" + new Gson().toJson(response.body().getData()));Log.e(TAG, "id" + String.valueOf(data.getId()));Log.e(TAG, "email" + String.valueOf(data.getEmail()));结束();开始活动(新意图(SignInActivity.this,HomeScreenActivity.class));overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);String message = response.body().getMessage();Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_SHORT).show();} 别的 {字符串数据 = response.body().getMessage();警报对话失败(数据);Log.e(TAG, "数据--" + 数据);dialog.dismiss();}} catch (NullPointerException e) {e.printStackTrace();}}/* 获取失败响应*/@覆盖public void onFailure(Call call, Throwable t) {dialog.dismiss();Log.e("错误", "" + String.valueOf(t.getMessage()));}});} 捕获(异常 e){e.printStackTrace();}}

请检查我的代码如何使用改造

希望对你有帮助

I'm trying to use Android Retrofit for the first time, I'm following tutorial and get stuck in on of the first steps... 1. Using Gson2.3, okhttp2.1.0, okhttp-urlconnection2.1.0, retrofit-1.8.0 2. my web service is in .php script and returns this kind of data {"idInfo":"12","typeInfo":"2"} 3. I created model class gitmodel

public class gitmodel {
    public gitmodel(int idInfo, int typeInfo) {
        this.idInfo = idInfo;
        this.typeInfo = typeInfo;
    }

    private int idInfo;
    private int typeInfo;
    public gitmodel() {
    }
    public int getIdInfo() {
        return idInfo;
    }
    public void setIdInfo(int idInfo) {
        this.idInfo = idInfo;
    }
    public int getTypeInfo() {
        return typeInfo;
    }
    public void setTypeInfo(int typeInfo) {
        this.typeInfo = typeInfo;
    }
}

" 4. I created interface class gitapi that looks like this

public interface gitapi {

    @GET("/users/{user}")      
    public void getFeed(@Path("user") String user,Callback<gitmodel> response);      
}

I get an error in this class "cannot resolve Path" and cannot resolve gitmodel. I know this is just a start but I cannot go on.

解决方案

Try these following steps:

  1. Add gradle and sync your project

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

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

  1. create your pojo class and add in model class like this

     public class LoginModel {
     @SerializedName("code")
     @Expose
     private String code;
     @SerializedName("message")
     @Expose
     private String message;
     @SerializedName("data")
     @Expose
      private Data data;
    
       public String getCode() {
       return code;
       }
    
      public void setCode(String code) {
      this.code = code;
     }
    
     public String getMessage() {
     return message;
     }
    
     public void setMessage(String message) {
     this.message = message;
     }
    
     public Data getData() {
      return data;
     }
    
    public void setData(Data data) {
    this.data = data;
    }
    
    public class Data {
    
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("facebookId")
    @Expose
    private String facebookId;
    @SerializedName("password")
    @Expose
    private String password;
    @SerializedName("securityHash")
    @Expose
    private String securityHash;
    @SerializedName("userName")
    @Expose
    private String userName;
    @SerializedName("firstName")
    @Expose
    private String firstName;
    @SerializedName("lastName")
    @Expose
    private String lastName;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("contact")
    @Expose
    private String contact;
    @SerializedName("userLastLoggedIn")
    @Expose
    private String userLastLoggedIn;
    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("createdAt")
    @Expose
    private String createdAt;
    @SerializedName("updatedAt")
    @Expose
    private String updatedAt;
    @SerializedName("profileStatus")
    @Expose
    private String profileStatus;
    @SerializedName("gender")
    @Expose
    private String gender;
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getFacebookId() {
        return facebookId;
    }
    
    public void setFacebookId(String facebookId) {
        this.facebookId = facebookId;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getSecurityHash() {
        return securityHash;
    }
    
    public void setSecurityHash(String securityHash) {
        this.securityHash = securityHash;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getFirstName() {
        return firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    
    public String getLastName() {
        return lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    
    public String getEmail() {
        return email;
    }
    
    public void setEmail(String email) {
        this.email = email;
    }
    
    public String getContact() {
        return contact;
    }
    
    public void setContact(String contact) {
        this.contact = contact;
    }
    
    public String getUserLastLoggedIn() {
        return userLastLoggedIn;
    }
    
    public void setUserLastLoggedIn(String userLastLoggedIn) {
        this.userLastLoggedIn = userLastLoggedIn;
    }
    
    public String getStatus() {
        return status;
    }
    
    public void setStatus(String status) {
        this.status = status;
    }
    
    public String getCreatedAt() {
        return createdAt;
    }
    
    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }
    
    public String getUpdatedAt() {
        return updatedAt;
    }
    
    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }
    
    public String getProfileStatus() {
        return profileStatus;
    }
    
    public void setProfileStatus(String profileStatus) {
        this.profileStatus = profileStatus;
    }
    
    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
    
    }
    }
    

  2. add three class in your package

  • RetrofitApiInterfaces
  • RetrofitClient
  • RetrofitConstent

1.1 Add RetrofitApiInterface Calss like this:


 public interface RetrofitApiInterface {

/*Login API Post Method*/
@POST("login")
@FormUrlEncoded
Call<LoginModel> loginMethod(@Field("email") String email, @Field("password") String password);
 }

1.2 Add RetrofitClient calss


public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url){
    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
}

1.3 Add RetrofitConstent class


public class RetrofitConstent {
public static String BASE_URL="";

public static RetrofitApiInterface retrofitApiInterface(){
    return RetrofitClient.getClient(BASE_URL).create(RetrofitApiInterface.class);
}
 }

4. Add Retrofit api method like this


   /*simple login API method*/
public void loginAPIMethod(String email, String password) {
    dialog = new Dialog(this, android.R.style.Theme_Translucent);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom_progress_dialog);
    dialog.setCancelable(false);
    dialog.show();
    Call<LoginModel> call = null;
    try {
        call = YabbyConstant.retrofitApiInterface().loginMethod(email, password);
        call.enqueue(new Callback<LoginModel>() {
            @Override
            public void onResponse(Call<LoginModel> call, Response<LoginModel> response) {
                /*getting success response */
                Log.e(TAG + "Response", "" + response.body().getCode());
                try {
                    if (response.body().getCode().equalsIgnoreCase("1")) {
                        dialog.dismiss();
                        LoginModel.Data data = response.body().getData();
                        /*save data into shared preference*/
                        Preference.storeUserPreferences(SignInActivity.this, ApiUtils.USER, new Gson().toJson(response.body().getData()));
                        Log.e(TAG, "sharedLogin" + new Gson().toJson(response.body().getData()));
                        Log.e(TAG, "id" + String.valueOf(data.getId()));
                        Log.e(TAG, "email" + String.valueOf(data.getEmail()));
                        finish();
                        startActivity(new Intent(SignInActivity.this, HomeScreenActivity.class));
                        overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
                        String message = response.body().getMessage();
                        Toast.makeText(getApplicationContext(), "" + message, Toast.LENGTH_SHORT).show();
                    } else {
                        String data = response.body().getMessage();
                        alertDialogueFail(data);
                        Log.e(TAG, "data--" + data);
                        dialog.dismiss();
                    }
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }

            /* getting failure response*/
            @Override
            public void onFailure(Call<LoginModel> call, Throwable t) {
                dialog.dismiss();
                Log.e("Error", "" + String.valueOf(t.getMessage()));
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Please Check my code how retrofit used

i hope its helps you

这篇关于Android Retrofit 简单使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆