初次使用Retrofit和Gson

直接贴源码,供自己继续学习。


写在前面:

添加依赖库是必须的。

dependencies {
    //添加retrofit和gson的依赖。
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    compile 'com.google.code.gson:gson:2.8.1'
}


首先定义一个接口类,相当于路由集合:


public interface RequestServes {
    @POST("user")
    Call register(@Query("phone") String phone,
                           @Query("password") String password);
    @GET("user")
    Call login(@Query("phone") String phone,
                       @Query("password") String password);
}

其次定义一个实体类,用来解析请求结果:


public class User {
    private String name,phone,password,created_at,updated_at;

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }
}


然后在活动总进行请求:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Retrofit retrofit;
    EditText phone,password;
    Button login,register;
    TextView result;
    SharedPreferences user;
    SharedPreferences.Editor editor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        retrofit = new Retrofit.Builder()
                .baseUrl("http://a.95home.top/")
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create())
                //增加返回值为Oservable的支持
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        phone = (EditText) findViewById(R.id.phone_edit);
        password = (EditText) findViewById(R.id.password_edit);
        login = (Button) findViewById(R.id.btn_login);
        register = (Button) findViewById(R.id.btn_register);
        result = (TextView) findViewById(R.id.show_response);
        login.setOnClickListener(this);
        register.setOnClickListener(this);
        user = getSharedPreferences("user",MODE_PRIVATE);
        editor = user.edit();
    }
    public void register(){
        String phone = this.phone.getText().toString();
        String password = this.password.getText().toString();
        RequestServes requestServes = retrofit.create(RequestServes.class);//这里采用的是Java的动态代理模式
        Call call = requestServes.register(phone,password);//传入我们请求的键值对的值
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                //Toast.makeText(MainActivity.this,"请求成功",Toast.LENGTH_LONG).show();
                //Log.e("===","return:"+response.body().toString());
                try {
                    JSONObject resp = new JSONObject(response.body().toString());
                    if ("success".equals(resp.getString("status"))){
                        Gson gson = new Gson();
                        /**
                         * 用Gson解析json
                         * 注意:User 中的成员变量名要和Json中键名一致,名称一致,数量一致
                         */
                        User user = gson.fromJson(resp.getString("user"),User.class);
                        Log.e("name","return:"+user.getName());
                        Log.e("phone","return:"+user.getPhone());
                        Log.e("password","return:"+user.getPassword());
                        Log.e("createTime","return:"+user.getCreated_at());
                        Log.e("updateTime","return:"+user.getUpdated_at());
                        editor.putString("name",user.getName());
                        editor.putString("phone",user.getPhone());
                        editor.putString("password",user.getPassword());
                        editor.commit();
                        result.setText(user.getPhone());
                    } else {
                        Log.e("msg","return:"+resp.getString("msg"));
                        result.setText(resp.getString("msg"));

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

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.e("===","失败");
            }
        });
    }

    public void login(){
        String phone = this.phone.getText().toString();
        String password = this.password.getText().toString();
        RequestServes requestServes = retrofit.create(RequestServes.class);//这里采用的是Java的动态代理模式
        Call call = requestServes.login(phone,password);//传入我们请求的键值对的值
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                //Toast.makeText(MainActivity.this,"请求成功",Toast.LENGTH_LONG).show();
                //Log.e("===","return:"+response.body().toString());
                try {
                    JSONObject resp = new JSONObject(response.body().toString());
                    if ("success".equals(resp.getString("status"))){
                        Gson gson = new Gson();
                        User user = gson.fromJson(resp.getString("user"),User.class);
                        Log.e("name","return:"+user.getName());
                        Log.e("phone","return:"+user.getPhone());
                        Log.e("password","return:"+user.getPassword());
                        editor.putString("name",user.getName());
                        editor.putString("phone",user.getPhone());
                        editor.putString("password",user.getPassword());
                        editor.commit();
                        result.setText(user.getPhone());
                    } else {
                        Log.e("msg","return:"+resp.getString("msg"));
                        result.setText(resp.getString("msg"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                Log.e("===","失败");
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.btn_login:
                login();
                break;
            case R.id.btn_register:
                register();
                break;
            default:
                break;
        }
    }
}

最后贴上简单的布局文件:

xml version="1.0" encoding="utf-8"?>
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
            android:layout_width="match_parent"
        android:layout_height="wrap_content">
                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="phone"/>
                    android:id="@+id/phone_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
            android:layout_width="match_parent"
        android:layout_height="wrap_content">
                    android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="password"/>
                    android:id="@+id/password_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    
            android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/btn_login"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="login"/>
        <Button
            android:id="@+id/btn_register"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="register"
            android:layout_weight="1"/>
    
            android:id="@+id/show_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


写在后面:

其实我也还没明白是什么原理。先用起来吧。慢慢研究。路漫漫其修远兮。。。。。。。。。。。。。。。。。。

你可能感兴趣的:(Android学习)