初次使用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<String> register(@Query("phone") String phone,
                           @Query("password") String password);
    @GET("user")
    Call<String> 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<T>的支持
                .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<String> call = requestServes.register(phone,password);//传入我们请求的键值对的值
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> 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<String> 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<String> call = requestServes.login(phone,password);//传入我们请求的键值对的值
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> 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<String> 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"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="phone"/>
        <EditText
            android:id="@+id/phone_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="password"/>
        <EditText
            android:id="@+id/password_edit"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        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"/>
    </LinearLayout>
    <TextView
        android:id="@+id/show_response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

写在后面:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值