android 实现登录功能

在一次实验中,老师的登录的后台传值没有使用@RequestBody而我的使用了 所以来记录一下 不同之处

老师的

public Result<UserInfoEntity> login(String userName, String userPwd, String verifyCode, HttpServletRequest request)

我的

public Result login(@Validated @RequestBody LoginDTO loginDTO, HttpServletRequest request){

首先在这里说明一下
使用和不使用@RequestBody的区别

1.
如果使用@RequestBody接受页面参数:
public Map<String,Object> insertBudget(@ApiParam(required = true,name = "actBudgetCost",value = "预算")@RequestBody ActBudgetCost actBudgetCost, HttpServletRequest request){

}

那么前台页面ajax应该这样写:
$.ajax({
        url: '',
        type: "POST",
        data: JSON.stringify({
            "actiName":name
        }),
        dataType: "json",
        contentType: "application/json",
        async: false,
        success: function (result) {

        },
        error: function (xhr, ajaxOptions, thrownError) {
            //console.log(thrownError); //alert any HTTP error
            //alert("请求出错!");
            return false;
        }
    });

2.
如果不使用@RequestBody接受页面参数:
public Map<String, Object> regProduct(HttpServletRequest request,
                                           @ApiParam(name = "customerProAuditPO", value = "产品注册实体")CustomerProAuditVO customerProAuditVO
    ) {

}

那么前台页面ajax应该这样写:
var data = {
    customerName:customerName,
};
$.ajax({
        url:'',
        type: "POST",
        data: data, 
        //async: false,
        dataType:"json",
        success: function(result) {
            var json = result;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError);
            return false;
        }
    });

老师的登录方法如下:

 private void login(){
        OkHttpClient client = HttpUtils.getClient();
        String userName = userNameEdit.getText().toString();
        String userPwd = userPwdEdit.getText().toString();
        String verifyCode = verifyCodeEdit.getText().toString();
        if (userName.equals("")) {
            showMsg("用户名不能为空");
            return;
        }
        if (userPwd.equals("")) {
            showMsg("密码不能为空");
            return;
        }
    if (verifyCode.equals("")) {
            showMsg("验证码不能为空");
            return;
        }
    RequestBody formBody = new FormBody.Builder()
            .add("userName", userName)
            .add("userPwd", userPwd)
            .add("verifyCode", verifyCode)
            .build();
    final Request request = new Request.Builder()
            .url(APPConfig.LOGIN_URL)
            .post(formBody)
            .build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //此处涉及到ui操作,只能在主线程中操作ui
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showMsg("请求服务器失败");
                }
            });
        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
            
   Result result = JSON.parseObject(response.body().string(),Result.class);
                    if(result.getCode() == 200){
                        showMsg("登录成功");
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);
                        finish();
                    }else{
                            showMsg(result.getMsg());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });
    }

当我是用老师的代码的时候
出现以下错误:

Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not
supported

所以将老师的代码改成如下方式取请求后台

private void login(){
        OkHttpClient client = HttpUtils.getClient();
        String userName = userNameEdit.getText().toString();
        String userPwd = userPwdEdit.getText().toString();
        String captcha = verifyCodeEdit.getText().toString();
        if (userName.equals("")) {
            showMsg("用户名不能为空");
            return;
        }

        if (userPwd.equals("")) {
            showMsg("密码不能为空");
            return;
        }

        if (captcha.equals("")) {
            showMsg("验证码不能为空");
            return;
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("userName", userName);
            json.put("userPwd", userPwd);
            json.put("captcha", captcha);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
//        RequestBody formBody = new FormBody.Builder()
//                .add("userName", userName)
//                .add("userPwd", userPwd)
//                .add("verifyCode", captcha)
//                .build();
        final Request request = new Request.Builder()
                .url(AppConfig.LOGIN_URL)
                .post(requestBody)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //此处涉及到ui操作,只能在主线程中操作ui
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showMsg("请求服务器失败");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Result result;
                            result = JSONObject.parseObject(response.body().string(),Result.class);
                            if(result.getCode() == 200){
                                showMsg("登录成功");
                                Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                showMsg(result.getMsg());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

然后就成功了

在运行过程中还出现了

android.os.NetworkOnMainThreadException

问题描述和解决办法如下:
https://blog.csdn.net/qq_29477223/article/details/81027716

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐