0

I have an android application. I have to get data from server through httppost with two parameter. But I always got response code 401 every time. It should be 200.

Here is my log file:

enter image description here

Here is my activity:

public class LoginActivity extends Activity implements OnClickListener {

Button login;
EditText user, pass;
CheckBox ck;
String FILENAME = "check";
String checkenords;

String FILETOKEN = "token";
String tokenStr;

String FILEEmail = "email";
String emailStr;

String responseStr;
String usernamefromuser;
int responsecode;
String passfromuser;
ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.sign_in);
    user = (EditText) findViewById(R.id.editText1);
    pass = (EditText) findViewById(R.id.editText2);
    ck = (CheckBox) findViewById(R.id.checkBox1);
    login = (Button) findViewById(R.id.btnlogin);

    login.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    new GetContacts().execute();
}

private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        usernamefromuser = user.getText().toString();
        passfromuser = pass.getText().toString();

        Log.e("successss", "888888888888");
        Log.e("Username", "User:" + usernamefromuser);
        Log.e("Password", "pass:" + passfromuser);
        HttpClient client = new DefaultHttpClient();
        String url = "http://54.228.199.162/api/auth";
        HttpPost httppost = new HttpPost(url);
        // httppost.setHeader("Content-type", "application/json");
        // httppost.setHeader("Accept", "application/json");

        try {
            List<NameValuePair> namevalpair = new ArrayList<NameValuePair>();
            namevalpair.add(new BasicNameValuePair("pass", passfromuser));
            namevalpair.add(new BasicNameValuePair("email",
                    usernamefromuser));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                    namevalpair, HTTP.UTF_8);
            httppost.setEntity(entity);
            HttpResponse httpresponse = client.execute(httppost);
            responsecode = httpresponse.getStatusLine().getStatusCode();
            responseStr = EntityUtils.toString(httpresponse.getEntity());
            Log.d("Authentication", "" + responsecode);
            // Log.d("httpresponseeeee", httpresponse.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        ;

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (responsecode == 200) {
            tokenStr = responseStr;
            emailStr = usernamefromuser;
            try {
                FileOutputStream fos = openFileOutput(FILETOKEN,
                        Context.MODE_PRIVATE);
                fos.write(tokenStr.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                FileOutputStream fos = openFileOutput(FILEEmail,
                        Context.MODE_PRIVATE);
                fos.write(emailStr.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            if (ck.isChecked()) {
                checkenords = "enable";
                try {
                    FileOutputStream fos = openFileOutput(FILENAME,
                            Context.MODE_PRIVATE);
                    fos.write(checkenords.getBytes());
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Intent inteGps = new Intent(LoginActivity.this, Gps.class);
                startActivity(inteGps);
                finish();
            } else {
                Intent inteGps = new Intent(LoginActivity.this, Gps.class);
                startActivity(inteGps);
                finish();
            }
        } else if (responsecode == 401) {

            Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.userwrong),
                    Toast.LENGTH_LONG).show();

        } else{
            Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.tryagain), Toast.LENGTH_LONG).show();
        }
        pDialog.dismiss();
    }
}
}

EDITED WITH POSTMAN enter image description here

Mohammad Rajob
  • 743
  • 1
  • 11
  • 28

3 Answers3

0

I suggest you to test your REST api (url) by using cURL or for quick setup use any google crome apps like POSTMAN google chrome extension which helps you test the REST api's in a easiest way!

if your rest api works fine then consider about using that your code, step by step try to trace whether server implementation is wrong or client side implementation wrong or url, parameters are wrong ! also check for <uses-permission android:name="android.permission.INTERNET" /> in your AndroidManifest.xml

enter image description here

public String userSignIn(String user, String pass, String authType)
            throws Exception {



        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://example/authenticate";


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


        nameValuePairs.add(new BasicNameValuePair("userName", user));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        // Add more parameters as necessary

        // Create the HTTP request
        HttpParams httpParameters = new BasicHttpParams();

        // Setup timeouts
        HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
        HttpConnectionParams.setSoTimeout(httpParameters, 15000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httppost = new HttpPost(
                url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
    String responseString = EntityUtils.toString(response.getEntity());
            Log.d("resp test", responseString);
    }

Edit:

try with

DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

source: SO

if you tired of using asynch task use volley which minimizes the code of http clients and it's more efficient

Community
  • 1
  • 1
LOG_TAG
  • 19,011
  • 12
  • 70
  • 103
0
Use bellow line in your code.....



HttpParams httpParams = new BasicHttpParams();

HttpClient httpClient = new DefaultHttpClient(httpParams);

HttpPost requestPost = new HttpPost(url);

requestPost.setHeader("*_*****_USERNAME", "admin******");

requestPost.setHeader("*_*****_PASSWORD", "admin@*****");

requestPost.setHeader("Content-Type","application/x-www-form-urlencoded");
//(as per your requirement)

I hope it will Work for u.....

Pratik Butani
  • 56,749
  • 54
  • 254
  • 407
Ashish
  • 21
  • 3
0

As per your Edited Question, I think you have to use HttpGet to send your authentication on Server.

Here I found example of HttpGet request in Android.

and also Here found StackOverflow Solution.

EDITED:

I have checked your POSTMAN and found that your server accepting JSON Data. You can see in Image:

enter image description here

so now you have to try this code:

   @Override
    protected Void doInBackground(Void... arg0) {

    // Creating service handler class instance
    usernamefromuser = user.getText().toString();
    passfromuser = pass.getText().toString();

    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("email", usernamefromuser);
        jsonObject.accumulate("pass", passfromuser);

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        responsecode = httpresponse.getStatusLine().getStatusCode();
        responseStr = EntityUtils.toString(httpresponse.getEntity());

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return null;
}

Sorry for late found the solution.

Community
  • 1
  • 1
Pratik Butani
  • 56,749
  • 54
  • 254
  • 407