简体   繁体   English

org.json.JSONException:值<HTML><HEAD>

[英]org.json.JSONException: Value <HTML><HEAD><STYLE of type java.lang.String cannot be converted to JSONObject

can someone please help me figure out what is wrong i am trying to connect my android application to mysql database for a simple login screen using php and json. 有人可以帮我找出问题所在吗,我正在尝试将我的android应用程序连接到mysql数据库,以便使用php和json实现简单的登录屏幕。 that is the first error i am getting in the logcat could somebody tell me what the problem is. 这是我在logcat中遇到的第一个错误,有人可以告诉我问题出在哪里。 is it my php file or json code 是我的php文件还是json代码

<?php
//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
//gets user's info based off of a username.
$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    // For testing, you could use a die and message. 
    //die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one to product JSON data:
    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}


$validated_info = false;

//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
    //if we encrypted the password, we would unencrypt it here, but in our case we just
    //compare the two passwords
    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}


if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));
} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
}
} else {
?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value=""                                              `enter code here`/> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php
}

?> 


package com.example.mysqltest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
  import org.apache.http.client.methods.HttpGet;
 import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

Code: 码:

public class JSONParser {

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

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

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

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

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

    // Return the JSON Object.
    return jObj;

}


// 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();

        }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("Buffer Error", "Error converting result " + e.toString());
    }

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

    // return JSON String
    return jObj;

   }
 }

Remove any HTML from the PHP Script such as: 从PHP脚本中删除所有HTML,例如:

} else {
?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <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
}

Because JSON API are supposed to only echo JSON data. 因为JSON API应该只回显JSON数据。

Also Add the following to the top of your PHP: 还将以下内容添加到PHP的顶部:

header('Content-type: application/json');

暂无
暂无

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

相关问题 错误org.json.JSONException:值 <html><head><title>无法将类型为java.lang.String的错误转换为JSONObject - Error org.json.JSONException: Value <html><head><title> Error of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值 - org.json.JSONException: Value <style of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值<html><body> - org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONObject 错误:org.json.JSONEXception:类型为java.lang.String的值访问无法转换为JSONObject - error: org.json.JSONEXception: Value Access of type java.lang.String cannot be converted to JSONObject 如何修复:org.json.JSONException:类型java.lang.String的值不能转换为JSONObject - How to fix: org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject org.json.JSONException:值类型为java.lang.String的数据不能转换为JSONObject - org.json.JSONException: Value Data of type java.lang.String cannot be converted to JSONObject org.json.JSONException:java.lang.String 类型的值 HTTP 无法转换为 JSONObject - org.json.JSONException: Value HTTP of type java.lang.String cannot be converted to JSONObject 解析数据org.json.JSONException时出错:值 - Error parsing data org.json.JSONException: Value <!— of type java.lang.String cannot be converted to JSONObject 错误。 org.json.JSONException:值 - error. org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject android错误org.json.JSONException:值 - android error org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM