3

我正在尝试在 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

谁能告诉我该怎么办谢谢

4

1 回答 1

-1

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

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

最后,您确定将密码发送给您的客户是个好主意吗...?(从您尝试从响应中读取它们的事实来看,我猜您正在尝试这样做)

于 2012-12-31T12:52:29.233 回答