HTTP请求返回null对象

时间:2015-06-17 05:38:14

标签: java php android http

我的代码只是从服务器上抛回一个空对象,我不知道它是否是我试图获取信息的方式,或者我甚至都不知道。你能看到什么明显的东西吗?

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

// constructor
public JSONParser() {

}

 // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                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();

                Log.e("Zam", httpEntity.toString());
            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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 + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            //Log.e("Zam", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            //Log.e("Zam", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

这是我从

调用它的地方
 class AttemptLogin extends AsyncTask<String, String, String>{

    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LogInActivity.this);
        pDialog.setMessage("Attempting to log you in");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        //pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        int success;
        String email = emailET.getText().toString();
        String pass = passwordET.getText().toString();

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", email));
            params.add(new BasicNameValuePair("password", pass));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                    LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(LogInActivity.this, MainActivity.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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


        return null;
    }

    @Override
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        if(file_url != null){
            Toast.makeText(LogInActivity.this, file_url, Toast.LENGTH_LONG).show();
        }
    }
}

服务器端

    <?php

require("config.inc.php");

if(!empty($_POST)){

    $query = "
      SELECT
        email
        password
        From users
        WHERE email = :email
    ";

    $queryParams = array(
        ':email' => $_POST['email']
    );

    try{

        $stmt = $db->prepare($query);
        $result = $stmt->execute($queryParams);

    }catch (PDOException $ec){
        $response["success"] = 0;
        $response["message"] = "Database Error1. unknown email address!";
        die(json_encode($response));

    }

    $row = $stmt->fetch();
    $loginOk = false;


    if($row){

        if($_POST['password'] === $row['password']){
            $loginOk = true;
        }

    }

    if($loginOk ===  true){
        $response["success"] = 1;
        $response["message"] = "logged in";
        die(json_encode($response));
    } else{
        $response["success"] = 0;
        $response["message"] = "wrong password";
        die(json_encode($response));
    }

}else{
?>
    <h1>Login</h1>

    <form action="login.php" method="post">

        Email:<br />

        <input type="text" name="email" placeholder="email" />

        <br /><br />

        Password:<br />

        <input type="password" name="password" placeholder="password" value="" />

        <br /><br />

        <input type="submit" value="Login" />

    </form>

    <a href="register.php">Register</a>

<?php

}

1 个答案:

答案 0 :(得分:0)

好吧,这是一个错误的URL设置和没有正确权限的组合,但现在已经修好了谢谢你