Accessing a login api using http get method in android

痴心易碎 提交于 2019-12-25 07:01:14

问题


I am developing an android app which uses a login api, which will allow its web users to login with their same credentials on the android device.....

the url for the api is

https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user=ecoachguest&pass=ecoachguest

which retuns a response in json

JSON object: {
    status: <success or error>,
    msg: <response message>,
    profile: <user profile object> 
}

I tried this code which I found searching on the internet but it isn't working,

private void doLogin(View view) {
    //ALERT MESSAGE
          _spinner.setVisibility(View.VISIBLE);
    Toast.makeText(mContext, "connecting to server.... ",
            Toast.LENGTH_SHORT).show();


    // URLEncode user defined data


    String usernameValue   = username.getText().toString();

    String passValue    = password.getText().toString();


    // Create http cliient object to send request to server

    HttpClient Client = new DefaultHttpClient();

    // Create URL string

    String URL = "https://api.ecoachsolutions.com/main.php?ecoachsignin=1&server=remote&user="+usernameValue+"&pass="+passValue;

    Log.i("httpget", URL);

    try
    {
        String SetServerString ;

        // Create Request to server and get response
        HttpGet httpget = new HttpGet(URL);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        SetServerString = Client.execute(httpget, responseHandler);

        System.out.println(usernameValue);
        System.out.println(passValue);
        // Show response on activity

        Toast.makeText(getBaseContext(),SetServerString,Toast.LENGTH_LONG).show();
    }
    catch(Exception ex)
    {
        Toast.makeText(getBaseContext(),"Fail",Toast.LENGTH_LONG).show();
        _spinner.setVisibility(View.INVISIBLE);
    }


}

will appreciate the help or the positive direction thanks :)


回答1:


Change your code to get the HttpResponse like below,

        String responseBody = "";

        HttpResponse response = client.execute(post);

        int responseCode = response.getStatusLine().getStatusCode();

        Log.i("GET Response Code ",responseCode + "");

        switch(responseCode) {
        // Means server is responding
        case 200:    
        HttpEntity entity = response.getEntity();
            if(entity != null) {
                responseBody = EntityUtils.toString(entity);
                // Now you can try printing your returned string here, before you go for JSON parsing
            }
            break;
        // Add more case statements to handle other scenarios
        }

The code is simple, but if still unable to understand, don't hesitate to ask.



来源:https://stackoverflow.com/questions/27253885/accessing-a-login-api-using-http-get-method-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!