如何检查服务器响应是否为json?

时间:2015-03-31 09:40:01

标签: android json jsonobject

当我尝试通过注册用户向数据库添加一些数据时,我的应用程序出现问题,问题是如果php脚本中有任何错误或者它没有返回json我收到错误并且活动被迫停止,而如果php中没有错误并正确返回json,一切正常,所以我想检查服务器响应,知道它是否有效,所以我可以避免错误,这里是我的代码:

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();
        }

    }
}

2 个答案:

答案 0 :(得分:2)

根据之前的评论:假设服务器正确设置响应的Content-Type标头字段,您可以在尝试处理响应主体之前检查该字段。

也就是说,如果返回json,则标头值应为application/json。如果返回错误(可能不是json格式,否则你的问题将是一个没有实际意义的点),例如它可能是text/htmltext/plain。只要服务器响应包含“成功”和“错误”的不同内容类型值,这究竟是什么并不重要。

检查Content-Type标题看起来有点像这样:

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
}

由您来实现实际行为并处理null值等。

答案 1 :(得分:1)

当您在onPostExecute()中得到respone时,只需尝试通过在JSONObject的构造函数中传递该响应将该字符串转换为json对象。见下面的代码

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

因此,如果您的输出是JSON格式,则Object已成功创建。另外,它会抛出异常。