Mohammad
Mohammad

Reputation: 3547

how to check if the server response is json or not?

I have a trouble in my app when I am trying to add some data to the db by registering a user, the problem is if there any error in the php script or it didn't returned json I got an error and the activity forced to stop, while if there are no errors in the php and returned json correctly, everything functions normally, so I want to check the server response to know if its valid or not, so I can avoid the error, here is my code:

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class Register  extends Activity {

    Button back;
    Button register;
    EditText iname;
    EditText iemail;
    EditText ireEmail;
    EditText ipassword;
    EditText irePassword;
    EditText iid;
    EditText iphone;
    EditText iaddress1;
    EditText iaddress2;


    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();

    // url to create new product
    private static String url_register = "http://192.168.0.103/perfectdelivery/register.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        iname = (EditText) findViewById(R.id.editText1);
        iemail = (EditText) findViewById(R.id.editText2);
        ireEmail = (EditText) findViewById(R.id.editText3);
        ipassword = (EditText) findViewById(R.id.editText4);
        irePassword = (EditText) findViewById(R.id.editText5);
        iid = (EditText) findViewById(R.id.editText6);
        iphone = (EditText) findViewById(R.id.editText7);
        iaddress1 = (EditText) findViewById(R.id.editText8);
        iaddress2 = (EditText) findViewById(R.id.editText9);

        back = (Button) findViewById(R.id.button1);
        register = (Button) findViewById(R.id.button2);

        back.setOnClickListener(myhandler1);
        register.setOnClickListener(myhandler2);
    }

    View.OnClickListener myhandler1 = new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(Register.this, MainPage.class);
            startActivity(intent);
        }
    };

    View.OnClickListener myhandler2 = new View.OnClickListener() {
        public void onClick(View v) {
            new NewAccount().execute();
        }
    };

    /**
     * Background Async Task to Create new product
     */
    class NewAccount extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Register.this);
            pDialog.setMessage("Registering...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         */
        protected String doInBackground(String... args) {
            String name = iname.getText().toString();
            String email = iemail.getText().toString();
            String reEmail = ireEmail.getText().toString();
            String password = ipassword.getText().toString();
            String rePassword = irePassword.getText().toString();
            String id = iid.getText().toString();
            String phone = iphone.getText().toString();
            String address1 = iaddress1.getText().toString();
            String address2 = iaddress2.getText().toString();



            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", name));
            params.add(new BasicNameValuePair("email", email));
            params.add(new BasicNameValuePair("password", password));
            params.add(new BasicNameValuePair("id", id));
            params.add(new BasicNameValuePair("phone", phone));
            params.add(new BasicNameValuePair("address1", address1));
            params.add(new BasicNameValuePair("address2", address2));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_register,
                    "POST", params);

            if(json != null) {

                // check log cat fro response
                Log.d("Create Response", json.toString());

                // check for success tag
                try {
                    int success = json.getInt(TAG_SUCCESS);

                    if (success == 1) {
                        // successfully created product
                        Intent i = new Intent(Register.this, MainPage.class);
                        startActivity(i);

                        // closing this screen
                        finish();
                    } else {
                        // failed to create product
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            else{

                Toast.makeText(getApplicationContext(), "An error occurred, please try again", Toast.LENGTH_LONG).show();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}

Upvotes: 0

Views: 4366

Answers (2)

Moinkhan
Moinkhan

Reputation: 12932

when you got the respone in onPostExecute() just try to convert that string into json object by passing that response in the constructor of JSONObject. see the below code

try {
     JSONObject json = new JSONObject("your_output");
} catch (JSONException e) {
     // your output is not in json format
     e.printStackTrace();
}

so, if your output is in JSON format the Object created successfully. other wise it will throw the exception.

Upvotes: 1

MH.
MH.

Reputation: 45493

As per an earlier comment: assuming the server correctly sets the Content-Type header field for the response, you could potentially check for that before attempting to handle the response body.

That is, if json is returned, the header value should be application/json. If an error is returned (which presumably isn't in json format, otherwise your question would be a moot point), it could for example be something like text/html or text/plain. Which exactly it is, doesn't really matter, as long as the server response contains different content type values for 'success' and 'error'.

Checking the Content-Type header will look somewhat like this:

HttpResponse response = ...
Header contentTypeHeader = response.getFirstHeader("Content-Type");
if ("application/json".equals(contentTypeHeader.getValue()) {
    // server returned json
} else {
    // server returned something else, potentially an error
}

Up to you to implement the actual behaviour and handle null values etc.

Upvotes: 4

Related Questions