繁体   English   中英

JSON响应一无所获

[英]JSON response getting nothing

我正在使用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分析器文件:

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)行返回任何内容。 以前,至少它仍然会从Web服务器返回分析代码错误。 最重要的是,后面是一个错误:

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程序。

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

试试这个代码

    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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM