Skip to content Skip to sidebar Skip to footer

Login Authentication With Post Method Android And Get The Other Apis Collection

I am very new in android developing. In my app I have a login page, where I want to implement authentication functionality by POST method. I have a root address through which I ha

Solution 1:

Here use this:

First to check whether internet is available or not.

publicbooleanisReachable(String address, int port, int timeoutMs) {
            try {
                Socketsock=newSocket();
                SocketAddresssockaddr=newInetSocketAddress(address, port);

                sock.connect(sockaddr, timeoutMs); // this will block no more than timeoutMs
                sock.close();

                returntrue;

            } catch (IOException e) { returnfalse; }
        }

then use volley library to hit the request:

publicbooleanauthenticateUsingServer(final String mEmail, final String mPassword){
            try {
                if(isReachable("8.8.8.8", 53, 1000)){
                    Log.e(TAG,"Authenticate using remote server");
                    // Instantiate the RequestQueue.RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
                    StringRequest strReq = newStringRequest(Request.Method.POST,
                            URL_LOGIN, newResponse.Listener<String>() {
                        @OverridepublicvoidonResponse(String response) {
                            Log.e(TAG, "Login Response: " + response);
                            //parse your response here
                           result = true;
                        }
                    }, newResponse.ErrorListener() {
                        @OverridepublicvoidonErrorResponse(VolleyError error) {
                            Log.e(TAG, "Login Error: " + error.getMessage());
                            Toast.makeText(getApplicationContext(),
                                    error.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }){

                        @OverrideprotectedMap<String, String> getParams() throws AuthFailureError {
                            Log.e(TAG,"Inside getParams");

                            // Posting parameters to login urlMap<String, String> params = newHashMap<>();
                            params.put("email", mEmail);
                            params.put("password", mPassword);

                            return params;
                        }

                    };
                    // Adding request to request queue
                    queue.add(strReq);
                    Thread.sleep(2000);
                }
                else{
                    Log.e(TAG,"Internet connection is required.");
                        /*Toast.makeText(LoginActivity.this,"Internet connectivity is required",
                                Toast.LENGTH_LONG).show();*/
                    result = false;
                    // TODO: exit the application
                }
            } catch (InterruptedException e) {
                returnfalse;
            }
            return result;
        }

then call it like this from Async task:

@OverrideprotectedBoolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            authenticateUsingServer(mEmail,mPassword);

            // TODO: register the new account here.returntrue;
        }

Solution 2:

Replace your LoginTask with following Code :

publicclassUserLoginTaskextendsAsyncTask<Void, Void, Boolean> {

    private final String mEmail;
    private final String mPassword;
    Activity instance ;

    UserLoginTask(String email, String password , Activity instance) {
        mEmail = email;
        mPassword = password;
        this.instance = instance ;
    }

    @OverrideprotectedBooleandoInBackground(Void... params) {
        // TODO: attempt authentication against a network service.JSONObject request = newJSONObject();
        request.put("email",mEmail );  
        request.put("pass",mPassword );             

        String result =  connectWithServer(instance , request);

        if(!TextUtils.isEmpty(result)){
            returntrue;
        }else{
            returnfalse;
        }

    }

    @OverrideprotectedvoidonPostExecute(final Boolean success) {
        mAuthTask = null;
        showProgress(true);
        if (success) {
            finish();
            Intent loginIntent = newIntent(LoginPage.this, MainActivity.class);
            startActivity(loginIntent);
        } else {
            userEmail.setError(getString(R.string.error_incorrect_password));
            userPassword.requestFocus();
        }
    }

    @OverrideprotectedvoidonCancelled() {
        mAuthTask = null;
        showProgress(false);

    }
}

Add connectWithServer() method in your Actvity class :

publicstatic String connectWithServer(Activity ctx , JSONObject request) {
    Stringresult="";
    try {
        //ConnectHttpURLConnectionurlConnection= (HttpURLConnection) ((newURL(YOUR_SERVICE_URL)).openConnection());
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();
        urlConnection.setConnectTimeout(100000);
        //WriteOutputStreamoutputStream= urlConnection.getOutputStream();
        BufferedWriterwriter=newBufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));

        writer.write(request.toString());
        writer.close();
        outputStream.close();

        //ReadBufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        Stringline=null;
        StringBuildersb=newStringBuilder();
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        bufferedReader.close();
        result = sb.toString();


    } catch (UnsupportedEncodingException e){
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (JSONException e){
        e.printStackTrace();
    }
    return result;
}

Post a Comment for "Login Authentication With Post Method Android And Get The Other Apis Collection"