org.json.JSONException无法在android中解析json响应

时间:2015-08-08 18:11:05

标签: android json

我正在开发一款需要用户登录和密码的应用。我的PHP脚本运行完美。但我的Android代码存在一些问题。在记录时我遇到了堆栈跟踪。这是我的代码

public class MainActivity extends AppCompatActivity
{
EditText userName;
EditText password;
Button sButton;
HttpClient httpClient;
HttpPost httpPost;
HttpResponse httpResponse;
String username;
String pass;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    userName = (EditText)findViewById(R.id.user_id);
    password = (EditText) findViewById(R.id.user_password);
    sButton= (Button) findViewById(R.id.s_button);
    username = userName.getText().toString();
    pass = password.getText().toString();
    httpClient = new DefaultHttpClient();

    httpPost = new HttpPost("http://192.168.100.106/EMS/functions.php");
    final JSONObject jsonObject = new JSONObject();


    sButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {
                Thread thread = new Thread()
                {
                    @Override
                    public void run()
                    {
                        try

                        {
                            jsonObject.put("username", username);
                            jsonObject.put("password", pass);
                            Log.wtf("Sent data :","username and password");
                            httpPost.setEntity(new StringEntity(jsonObject.toString()));
                        }

                        catch(JSONException | UnsupportedEncodingException e)

                        {
                            e.printStackTrace();
                        }
                        try {
                            httpResponse = httpClient.execute(httpPost);
                            Log.wtf("Request sent: "," httpresponse");
                            String str = EntityUtils.toString(httpResponse.getEntity());
                            Log.wtf("String recieved ",str);
                            JSONObject responseObject = new JSONObject(str);
                            String response = responseObject.getString("success");
                            Log.wtf("Response recieved ",response);
                            if(response.equals("1"))
                            {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(), "Credentials match successful.",Toast.LENGTH_SHORT).show();
                                        Intent intent = new Intent(MainActivity.this,index.class);
                                        startActivity(intent);

                                    }
                                });
                            }

                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };thread.start();



        }
    });
}

}

这是我的stackTrace

08-08 23:31:46.726  17362-17472/milind.com.ems A/Sent data :﹕ username and password
08-08 23:31:46.771  17362-17472/milind.com.ems A/Request sent:﹕ httpresponse
08-08 23:31:46.811  17362-17472/milind.com.ems A/String recieved﹕ [ 08-08     23:31:46.812 17362:17472 W/System.err ]
org.json.JSONException: End of input at character 2 of

我的Php脚本是:

<?php

class functions  
{
private $con;

function __construct() 
{
    require_once 'DB_Connect.php';
    $this->db = new DB_Connect();
    $this->con =$this->db->connect();
}
function __destruct() 
{

}

function getUser()
{
    $json= file_get_contents("php://input");
    $str = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($json));
    $str = json_decode($str,true);
    $ID = $str['username'];
    $password = $str['password'];
    $password = $this->clearstring($password);
    // echo "Password :- " . $password;
    $q="SELECT * FROM employers WHERE Employers_ID = '{$ID}' ";        
    $user =$this->con->query($q);        
    //echo mysqli_error($this->con);

    if($user->num_rows >0)
    {
        $row = $user->fetch_assoc();           
        $db_password = $row['Password'];            
        $this->compare($db_password,$password);
    }

   }
    function clearstring($str)
    {
        //$str = strip_tags($str);
        $str = stripcslashes($str);
        $str = htmlspecialchars($str);
        $str = trim($str);
    return $str;

    }
    function compare($db_str, $app_str)
    {   
       // $salt = "ol2ujh354238095uwef";
        $app_str = $app_str/*.$salt*/;
       //echo "<br>Database password:- ".$db_str;
       // echo "<br>Database password:- ".md5($app_str);             
        if(md5($app_str)==$db_str)
        {
            $response['success'] = '1';
        }
        else
        {
            $response['success'] = '0';
        }
        //echo json_encode($response);
        //$response = json_encode($response);
        die(json_encode($response));
        //mysqli_close($con);
    }            
}
  $func = new functions();
  $func->getUser();

?>

2 个答案:

答案 0 :(得分:1)

username = userName.getText().toString();
pass = password.getText().toString();

您应该在onClick方法上执行此操作,而不是on onCreate。

答案 1 :(得分:0)

嗯,你收到这个字符串:

[ 08-08     23:31:46.812 17362:17472 W/System.err ]

从服务器,这不是有效的JSON。 这一行:

JSONObject responseObject = new JSONObject(str);

尝试将该字符串解析为json并失败。

我认为你总是期待来自你服务器的JSON响应,所以我怀疑你的这句话:

  

我的PHP脚本运行完美。

是对的。您应该检查PHP服务器响应非JSON响应的原因。