【Android项目实战 | 从零开始写app(五)】okhttp+gson实现服务端注册功能

本篇实现效果:

使用Okhttp3进行联网请求,通过post方法把用户名和密码发送到服务进行校验,如果账户已存在则提示,注册成功后,使用Gson解析返回的json数据提示用户,如下:

(额,这里要说一下:提示逻辑处理有点问题,这里代码已经修改好了,但是gif中还没有,由于时间不是很多就不再录制一遍了,见谅~)
在这里插入图片描述

文章导航

一、【Android项目实战 | 从零开始写app(一)】 创建项目

二、【Android项目实战 | 从零开始写app(二)】实现闪屏页,启动app

三、【Android项目实战 | 从零开始写app(三)】实现引导页,进入登录or主页面

四、【Android项目实战 | 从零开始写app(四)】Okhttp+Gson实现服务端登录验证功能

五、【Android项目实战 | 从零开始写app(五)】okhttp+gson实现服务端注册功能

六、【Android项目实战 | 从零开始写app(六)】用TabLayout+ViewPager搭建App 框架主页面底部导航栏

七、【Android项目实战 | 从零开始写app(七)】优化主页导航栏,禁用主页页面滑动切换效果

八、【Android项目实战 | 从零开始写app(八)】实现app首页广告轮播图切换和搜索跳转

九、【Android项目实战 | 从零开始写app(九)】Tablayout+ViewPager实现页面分类顶部标题页面联动切换

十、【Android项目实战 | 从零开始写app(十)】Okhttp+glide+json+ListView实现新闻模块数据的填充显示

十一、【Android项目实战 | 从零开始写app(十一)】实现app首页智慧服务页面服务分类数据的解析及点击跳转

十二、【Android项目实战 | 从零开始写app(十二)】实现app首页智慧服务&热门推荐&热门主题、新闻

十三、【Android项目实战 | 从零开始写app(十三)】实现用户中心模块清除token退出登录&信息修改等功能

十四、【Android项目实战 | 从零开始写app(十四)】实现图片发布模块 | 必知必会之调用系统相机拍照、相册

十五、【Android项目实战 | 从零开始写app(教程汇总)】Android 项目实战系列汇总、源代码


逻辑功能实现:

RegisterActivity.class:

package com.example.myapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.CallLog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapp.R;
import com.example.myapp.bean.ResultBean;
import com.example.myapp.utils.APIConfig;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_nicke;
    private EditText et_phonr;
    private EditText et_password;
    private RadioButton rb_man;
    private RadioButton rb_woman;
    private RadioGroup rg_sex;
    private Button btn_register;
    private Button btn_login;

    private OkHttpClient client = new OkHttpClient();
    private Intent intent = null;

    String sex = "";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0) {
                String resultStr = (String) msg.obj;
                Log.i("获取返回的信息:",resultStr);
                final ResultBean resultBean = new Gson().fromJson(resultStr,ResultBean.class);
                int resultCode = resultBean.getCode();
                if (resultCode==200){
                    Toast.makeText(getApplicationContext(),"注册成功:"+resultStr,Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"注册失败:"+resultStr,Toast.LENGTH_LONG).show();
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        et_name = (EditText) findViewById(R.id.et_name);
        et_nicke = (EditText) findViewById(R.id.et_nicke);
        et_phonr = (EditText) findViewById(R.id.et_phone);
        et_password = (EditText) findViewById(R.id.et_password);
        rb_man = (RadioButton) findViewById(R.id.rb_man);
        rb_woman = (RadioButton) findViewById(R.id.rb_woman);
        rg_sex = (RadioGroup) findViewById(R.id.rg_sex);
        btn_register = (Button) findViewById(R.id.btn_register);
        btn_login = (Button) findViewById(R.id.btn_login);

        btn_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId==rb_man.getId()) {
                    sex="1";
                }else {
                    sex="0";
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_register:
                Register();
                break;
            case R.id.btn_login:
                intent = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void Register() {
        // validate
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        String nicke = et_nicke.getText().toString().trim();
        if (TextUtils.isEmpty(nicke)) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = et_phonr.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入你的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "password不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userName",name);
            jsonObject.put("nickName",nicke);
            jsonObject.put("phonenumber",phone);
            jsonObject.put("sex",sex);
            jsonObject.put("password",password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        final RequestBody requestBody =RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .post(requestBody)
                .url(APIConfig.URL_BASE+"/user/register")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Message msg = new Message();
                msg.what=0;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        });
    }



}

activity_rgister:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ECECEC"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="用户注册"
        android:layout_marginTop="50dp"
        android:textSize="30sp"
        android:textStyle="bold"
        android:layout_marginBottom="50dp"
        android:textColor="#202020"/>

    <LinearLayout
        android:paddingLeft="20dp"
        android:paddingRight="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@drawable/shape_login_form">
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用 户 名:"
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_name"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入用户名"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="你的昵称: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_nicke"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入昵称"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="手机号码: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_phone"
                android:textSize="16sp"
                android:background="@null"
                android:layout_margin="5dp"
                android:hint="请输入你的手机号码"/>
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="  密     码:"
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/et_password"
                android:textSize="16sp"
                android:background="@null"
                android:inputType="numberPassword"
                android:hint="请输入密码"
                android:layout_margin="5dp" />
        </LinearLayout>
        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:background="#DADADA"/>
        <LinearLayout
            android:layout_marginTop="12dp"
            android:layout_width="match_parent"
            android:layout_marginBottom="10dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="你的性别: "
                android:layout_marginTop="10dp"
                android:textSize="18sp"
                android:textColor="#000000"/>
            <RadioGroup
                android:id="@+id/rg_sex"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:orientation="horizontal">
                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:layout_marginRight="40dp"
                    android:id="@+id/rb_man"/>
                <RadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=""
                    android:id="@+id/rb_woman"/>
            </RadioGroup>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_marginRight="15dp"
        android:layout_marginLeft="15dp"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <Button
            android:layout_marginTop="30dp"
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:text="登录"
            android:textColor="#ffffff"

            android:background="@drawable/shape_login_btn"
            android:textSize="20sp" />
        <Button
            android:id="@+id/btn_register"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="20dp"

            android:background="@drawable/shape_register_btn"
            android:layout_alignParentRight="true"
            android:text="注册"
            android:textColor="#136BC8"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

ResultBean

package com.example.myapp.bean;

import java.util.List;

public class ResultBean {

    /**
     * total : 0
     * rows : []
     * code : 200
     * msg : 查询成功
     */

    private int total;
    private int code;
    private String msg;
    private List<?> rows;

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<?> getRows() {
        return rows;
    }

    public void setRows(List<?> rows) {
        this.rows = rows;
    }
}

工具类 utils

新建APIConfig.class ,放请求服务器的根网址

package com.example.myapp.utils;

/**
 * @ProjectName: MyApp
 * @Package: com.example.myapp.utils
 * @ClassName: APIConfig
 * @Description:
 * @Author: liyingxia
 * @CreateDate: 2021/4/13 17:46
 */
public class APIConfig {
    public final static String URL_BASE = "http://192.168.196.45:8080";
}

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
好的,以下是JavaAndroid retrofit okhttp rxjava代码的示例: 首先,在build.gradle文件中添加以下依赖: ``` implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' implementation 'io.reactivex.rxjava2:rxjava:2.2.10' ``` 然后,在你的Java类中,创建一个Retrofit实例: ```java public class RetrofitClient { private static Retrofit retrofit = null; public static Retrofit getClient(String baseUrl) { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(baseUrl) .client(getOkhttpClient()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } return retrofit; } private static OkHttpClient getOkhttpClient() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); return new OkHttpClient.Builder().addInterceptor(interceptor).build(); } } ``` 接下来,在你的Activity或Fragment中,定义一个接口: ```java public interface ApiService { @GET("api/data/{category}/{count}/{page}") Observable<Results> getData(@Path("category") String category, @Path("count") int count, @Path("page") int page); } ``` 在这个示例中,我们使用了Retrofit和RxJava获取远程数据。 最后,在你的代码中,调用Retrofit客户端并使用RxJava观察获取到的数据: ```java ApiService apiService = RetrofitClient.getClient(BASE_URL).create(ApiService.class); apiService.getData(category, count, page) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Results>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Results results) { // 处理从服务器获取到的数据 } @Override public void onError(Throwable e) { // 处理请求错误 } @Override public void onComplete() { } }); ``` 这就是一个简单的Android retrofit okhttp rxjava代码的示例。当然,具体的实现方式会根据不同的需求而有所变化。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值