JSONException:java.lang.string类型的值无法转换为JSONObject

时间:2012-12-31 12:45:29

标签: java php android json

我正在尝试在android中创建一个登录界面,我想连接到连接到数据库的php文件。 数据库名为“daymanager”,表格为“login”

这是一个名为login.php的php文件:

<?php

$host="localhost";
$user="root";
$pass="";
$dbname="daymanager";

$con= mysql_connect($host,$user,$pass);
$BD= mysql_select_db($dbname, $con);
//$username=$_POST['username'];
//$password=$_POST['password'];

$query=mysql_query("select username,password from login");
$num=mysql_num_rows($query);

if($num==1)
{
while($list=mysql_fetch_array($query))
{
$output=$row[username];
echo json_encode($output);

}
mysql_close();
}
?>

这是eclipse中的java代码:

package com.mounzer.test;





import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.HostNameResolver;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Activating extends Activity implements OnClickListener {
    Button login;
    EditText user,pass;
    String username,password;

    HttpClient httpclient;
    HttpPost httppost;
    ArrayList<NameValuePair> namevaluepairs;
    HttpResponse response;
    HttpEntity entity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub







        super.onCreate(savedInstanceState);
        setContentView(R.layout.activ);



        initialise();
    }

    private void initialise() {
        // TODO Auto-generated method stub
        login =(Button) findViewById(R.id.login);
        user=(EditText) findViewById(R.id.user);
        pass=(EditText) findViewById(R.id.pass);
        login.setOnClickListener(this);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub




        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        httpclient = new DefaultHttpClient();

        httppost =new HttpPost("http://192.168.48.1:6789/aglprojet/Login.php");


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



        try

        {
            namevaluepairs = new ArrayList<NameValuePair>();
            namevaluepairs.add(new BasicNameValuePair("username", username));
            namevaluepairs.add(new BasicNameValuePair("password", password));
            httppost.setEntity(new UrlEncodedFormEntity(namevaluepairs));
            response=httpclient.execute(httppost);

            if(response.getStatusLine().getStatusCode()==200)
            {
                entity=response.getEntity();

                if(entity !=null)
                {
                    InputStream instream=entity.getContent();
                    JSONObject jsonResponse=new JSONObject(convertStreamToString(instream));

                    String retUser = jsonResponse.getString("username");
                    String retPass = jsonResponse.getString("password");



                    if(username.equals(retUser) && password.equals(retPass))
                    {
                    SharedPreferences sp=getSharedPreferences("logindetails", 0);
                    SharedPreferences.Editor spedit=sp.edit();
                    spedit.putString("user",username);
                    spedit.putString("pass",password);
                        spedit.commit();


                        Toast.makeText(getBaseContext(),"Succesfully connected", Toast.LENGTH_SHORT).show();

                    }else {Toast.makeText(getBaseContext(),"Invalid username or password", Toast.LENGTH_SHORT).show(); }
                }


            }


        }catch(Exception e)

        {
            e.printStackTrace();
            Toast.makeText(getBaseContext(),e.toString(), Toast.LENGTH_LONG).show();
        }



    }
     private void Log(String string, String retUser) {
        // TODO Auto-generated method stub

    }

    private static String convertStreamToString(InputStream is) {
            /*
             * To convert the InputStream to String we use the BufferedReader.readLine()
             * method. We iterate until the BufferedReader return null which means
             * there's no more data to read. Each line will appended to a StringBuilder
             * and returned as String.
             */
          BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(null, e.toString(), Toast.LENGTH_SHORT).show();
                }
            }
            return sb.toString();
        }

}

当我从手机上试用该应用程序时,它给了我这个例外:

org.json.JSONException java.lang.string类型的值<html>无法转换为JSONObject

任何人都可以告诉我该怎么办 谢谢

1 个答案:

答案 0 :(得分:-1)

我的猜测是,某些内容遇到错误并返回包含在HTML中的错误消息。尝试通过浏览器或任何可以让您看到实际返回的内容来调用您的身份验证脚本。

此外,您似乎没有在输出中返回任何字段,因此getString("username")等永远不会起作用。如果要从身份验证脚本中返回多个内容,请将它们放入数组或其他内容json_encode

最后,您确定将密码发送给您的客户端是个好主意吗? (我猜你试图通过你试图从回复中读回它来判断这一点)