简体   繁体   English

当我从android调用post方法时返回json响应

[英]return json response when i call post method from android

I'm building a log In page where i call a restful api to check username and password validation, the api returns username Id if the status code is OK, i want to be able to store this id and use it later on 我正在构建一个登录页面,我在其中调用一个宁静的api来检查用户名和密码验证,如果状态代码正常,则该api返回用户名ID,我希望能够存储此ID并在以后使用

signin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                RequestQueue requestQueue = Volley.newRequestQueue(SignIn.this);
                String URL = "http://localhost/WebApplication7/api/login";
                JSONObject jsonBody = new JSONObject();
               // jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
                jsonBody.put("tblRegisteredUsers_UserName", username.getText().toString().trim());
                jsonBody.put("tblRegisteredUsers_Password", password.getText().toString().trim());



                final String requestBody = jsonBody.toString();

                StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        if (response.trim().equals("2013")) {
                            //login authenticated. Start the next activity of your app
                            Toast.makeText(SignIn.this, "Logged In", Toast.LENGTH_SHORT).show();

                            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                            startActivity(intent);
                        } else {
                            //login failed. prompt to re-enter the credentials
                            Toast.makeText(SignIn.this, "Failed to log In", Toast.LENGTH_SHORT).show();

                            Log.i("VOLLEY", response);
                            Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("VOLLEY", error.toString());
                    }
                }) {
                    @Override
                    public String getBodyContentType() {
                        return "application/json; charset=utf-8";
                    }

                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        try {
                            return requestBody == null ? null : requestBody.getBytes("utf-8");
                        } catch (UnsupportedEncodingException uee) {
                            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                            return null;
                        }
                    }

                    @Override
                    protected Response<String> parseNetworkResponse(NetworkResponse response) {
                        String responseString = "";
                        if (response != null) {
                            responseString = String.valueOf(response.statusCode);

// Toast.makeText(getApplicationContext(), responseString, Toast.LENGTH_SHORT).show(); // Toast.makeText(getApplicationContext(),responseString,Toast.LENGTH_SHORT).show(); // can get more details such as response.headers } return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response)); //可以获取更多详细信息,例如response.headers} return Response.success(responseString,HttpHeaderParser.parseCacheHeaders(response)); } }; };

                requestQueue.add(stringRequest);
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    });

this is my web api code (vb asp.net) 这是我的网络api代码(vb asp.net)

Public Function login(<FromBody> ByVal users As tblRegisteredUser) As IHttpActionResult
        Try
            Using entities As IAPD_DBEntities = New IAPD_DBEntities()
                Dim username = entities.tblRegisteredUsers.FirstOrDefault(Function(e) e.tblRegisteredUsers_UserName.Equals(users.tblRegisteredUsers_UserName))
                Dim password = entities.tblRegisteredUsers.FirstOrDefault(Function(e) e.tblRegisteredUsers_Password.Equals(users.tblRegisteredUsers_Password))
                If username Is Nothing OrElse password Is Nothing Then



                    Dim message = Request.CreateResponse(HttpStatusCode.BadRequest, "username or password is incorrect")
                    Return message
                Else
                    Dim response = Request.CreateResponse(HttpStatusCode.OK)
                    response.Content = New StringContent(username.tblRegisteredUsers_UserPKID.ToString.Trim.ToString, Encoding.UTF8, "application/json")
                    'Dim message = Request.CreateResponse(HttpStatusCode.Created, username.tblRegisteredUsers_UserPKID.ToString.Trim)
                    'message.Headers.Location = New Uri(Request.RequestUri, "Loged In successfully")
                    Return Ok(username.tblRegisteredUsers_UserPKID.ToString.Trim.ToString)
                End If
            End Using
        Catch e As Exception
            Return BadRequest(e.ToString)
        End Try
    End Function

and the response from the api is "2013"(the id of the username) how can i store this id, my problem is that i get response as code 200 not as the id of username any help would be appreciated 而且来自api的响应是“ 2013”​​(用户名的ID),我该如何存储此ID,我的问题是我得到的响应是代码200,而不是用户名的ID,因此不胜感激

Well, if you only want to store that value permanently for later use, you could either store it in Shared Preferences or in a database, it is up to you. 好吧,如果您只想永久存储该值以备后用,则可以将其存储在“共享首选项”中或数据库中,由您决定。 I personally rather using database for this kind of user data. 我个人宁愿使用数据库来存储此类用户数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM