0

我正在使用 Android 登录到托管在 000webohst.com 上的基于 php 的 Web 服务。这是我的主文件:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ccse);

    user = (EditText)findViewById(R.id.userid_edit);
    password = (EditText) findViewById(R.id.passwd_edit);
    lbl = (TextView) findViewById(R.id.label);
}

public void login(View view)
{
    String userID = user.getText().toString();
    String passWord = password.getText().toString();

    parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("tag", "login"));
    parameters.add(new BasicNameValuePair("userid", userID));
    parameters.add(new BasicNameValuePair("password", passWord));

    new loginTask().execute();

    Toast.makeText(this, "Login task executed!", Toast.LENGTH_LONG).show();
}

public class loginTask extends AsyncTask<Void, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(Void... params) {

        jsonParser = new JSONParser();

        return jsonParser.getJSONFromUrl(loginURL, parameters);
    }

     protected void onPostExecute(Void v) {

         try {

                if(json.getString("success") != null) {

                    JSONObject json_user = json.getJSONObject("user");

                    user.setText("");
                    password.setText("");

                    lbl.setText("Hello " + json_user.getString("name") );

                 }
                else {

                    lbl.setText("Error!");

                }

            } 
             catch (JSONException e) {

                e.printStackTrace();

            }
     } 

}

然后这是我的 JSON Parser 文件:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\r\n");
        }
        is.close();
        json = sb.toString();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
}

这是我试图连接的 PHP 文件:

        <?php

    header('Content-Type: application/json; charset=utf-8');
    require ('dbconnect.php');
    mysql_select_db("a7085864_ccse", $con) or die('Could not connect: ' . mysql_error());


    if(isset($_POST['tag']) && $_POST['tag'] != "") {

    $response=array("success" => 0, "error" => 0);

    $userid = $_POST['userid'];
    $password = $_POST['password'];

    $sql="select StudentName from student where StudentID='$userid' and StudentPw='$password'";
    $result=mysql_query($sql);

    $count=mysql_num_rows($result);

            if($count==1) {
                while($row = mysql_fetch_array($result)) {

                    $response["success"]=1;
                    $response["user"]["name"]=$row["StudentName"];
                    echo json_encode($response);
                }

            }

            else {

                $response["error"]=1;
                $response["error_msg"] = "Error logging in.";
                echo json_encode($response);

            }

    }
    else {

    echo json_encode("Error getting data!");

    }


    exit();

    ?>

但是,在 Logcat 上,我似乎没有看到我的 json 通过 Log.e("JSON",json) 行返回任何内容。以前,至少它仍然会从网络服务器返回一个分析代码错误。最重要的是,后面跟着一个错误:

05-06 01:06:33.511: E/JSON Parser(1835): Error parsing data org.json.JSONException: End of input at character 0 of 

知道是什么原因造成的吗?我无法弄清楚错误来自 PHP 脚本或 Android 程序。

4

2 回答 2

0

在你的login方法中。

它应该是。

public void login(View view)
{
    String userID = user.getText().toString();
    String passWord = password.getText().toString();

    parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("tag", "login"));
    parameters.add(new BasicNameValuePair("userid", userID));
    parameters.add(new BasicNameValuePair("password", passWord));

    new loginTask().execute();

    Toast.makeText(this, "Login task executed!", Toast.LENGTH_LONG).show();
}
于 2013-05-05T17:21:18.680 回答
0

试试这个代码

    public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            String json = EntityUtils.toString(httpResponse.getEntity());

            Log.e("JSON", json);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }

EntityUtils类来自包 -> org.apache.http.utils

于 2013-05-05T19:13:54.900 回答