org.json.JSONException:值< HTML>< HEAD>< java.lang.String类型风格不能转换到的JSONObject [英] org.json.JSONException: Value <HTML><HEAD><STYLE of type java.lang.String cannot be converted to JSONObject

查看:157
本文介绍了org.json.JSONException:值< HTML>< HEAD>< java.lang.String类型风格不能转换到的JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以请帮我找出什么是错的我试图我的android应用到mysql数据库连接使用PHP和JSON一个简单的登录屏幕。这是我在logcat中越来越能有人告诉我是什么问题的第一个错误。这是我的PHP文件或JSON code

 < PHP
//装载并连接到MySQL数据库的东西
要求(config.inc.php文件);如果(!空($ _ POST)){
//获取基于掀起了用户名用户的信息。
$查询=
        选择
            ID,
            用户名,
            密码
        来自用户的
        哪里
            用户名=:用户名
    $ query_params =阵列(
    :用户名=> $ _ POST [用户名]
);尝试{
    $语句= $ DB-GT&; prepare($查询);
    $结果= $ stmt->执行($ query_params);
}
赶上(PDOException $前){
    //为了测试,你可以使用模具和消息。
    //模具(无法运行的问题:$ EX->的getMessage());    //或使用此用这个产品JSON数据:
    $响应[成功] = 0;
    $响应[消息] =数据库ERROR1请重试!
    死亡(json_en code($响应));}
$ validated_info = FALSE;//从查询获取所有的行
$行= $ stmt->取();
如果($行){
    //如果我们加密的口令,我们就在这里解密,但在我们的例子中,我们只
    //比较两个密码
    如果($ _ POST ['密码'] === $行['密码']){
        $ login_ok = TRUE;
    }
}
如果($ login_ok){
    $响应[成功] = 1;
    $响应[消息] =登录成功!;
    死亡(json_en code($响应));
}其他{
    $响应[成功] = 0;
    $响应[消息] =!无效的凭证;
    死亡(json_en code($响应));
}
}其他{
?>
    < H1>登录和LT; / H1>
    <形式的行动=login.php中方法=后>
        用户名:其中; BR />
        <输入类型=文本名称=用户名占位符=用户名/>
        < BR />< BR />
        密码:LT; BR />
        <输入类型=密码NAME =密码占位符=密码值='输入code here` />
        < BR />< BR />
        <输入类型=提交值=登录/>
    < /表及GT;
    &所述; A HREF =register.php>寄存器&下; / A>
< PHP
}?>
包com.example.mysqltest;进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
 进口org.apache.http.client.entity.UrlEn codedFormEntity;
  进口org.apache.http.client.methods.HttpGet;
 进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.util.Log;

code:

 公共类JSONParser {静态InputStream为= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;//构造
公共JSONParser(){}
公众的JSONObject getJSONFromUrl(最终字符串URL){    //使HTTP请求
    尝试{
        //构建客户端和HTTP请求。
        DefaultHttpClient的HttpClient =新DefaultHttpClient();
        HttpPost httpPost =新HttpPost(URL);        //执行POST请求,并在本地存储的响应。
        HTT presponse HTT presponse = httpClient.execute(httpPost);
        //从响应中提取数据。
        HttpEntity httpEntity = HTT presponse.getEntity();
        //打开与数据内容的InputStream。
        是= httpEntity.getContent();    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
    }赶上(ClientProtocolException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }    尝试{
        //创建一个BufferedReader通过InputStream的解析。
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                是,ISO-8859-1),8);
        //声明一个字符串生成器,以帮助解析。
        StringBuilder的SB =新的StringBuilder();
        //声明一个字符串JSON对象数据存储在字符串形式。
        串线= NULL;        //生成字符串,直到空。
        而((行= reader.readLine())!= NULL){
            sb.append(行+\\ n);
        }        //关闭输入流。
        is.close();
        //字符串生成器的数据转换为实际的字符串。
        JSON = sb.toString();
    }赶上(例外五){
        Log.e(缓冲区错误,错误转换结果+ e.toString());
    }    //尝试将字符串解析到一个JSON对象
    尝试{
        jObj =新的JSONObject(JSON);
    }赶上(JSONException E){
        Log.e(JSON解析器,错误分析数据+ e.toString());
    }    //返回JSON对象。
    返回jObj;}
//函数得到JSON的网址
//通过HTTP POST或GET mehtod
公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
        清单<&的NameValuePair GT; PARAMS){    //使HTTP请求
    尝试{        //检查请求的方法
        如果(方法==POST){
            //请求方法是POST
            // defaultHttpClient
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            HttpPost httpPost =新HttpPost(URL);
            httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));            HTT presponse HTT presponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = HTT presponse.getEntity();
            是= httpEntity.getContent();        }否则如果(方法==GET){
            //请求方法是GET
            DefaultHttpClient的HttpClient =新DefaultHttpClient();
            字符串中的paramString = URLEn codedUtils.format(参数,可以UTF-8);
            网址+ =? +中的paramString;
            HTTPGET HTTPGET =新HTTPGET(URL);            HTT presponse HTT presponse = httpClient.execute(HTTPGET);
            HttpEntity httpEntity = HTT presponse.getEntity();
            是= httpEntity.getContent();
        }    }赶上(UnsupportedEncodingException五){
        e.printStackTrace();
    }赶上(ClientProtocolException E){
        e.printStackTrace();
    }赶上(IOException异常五){
        e.printStackTrace();
    }    尝试{
        读者的BufferedReader =新的BufferedReader(新的InputStreamReader(
                是,ISO-8859-1),8);
        StringBuilder的SB =新的StringBuilder();
        串线= NULL;
        而((行= reader.readLine())!= NULL){
            sb.append(行+\\ n);
        }
        is.close();
        JSON = sb.toString();
    }赶上(例外五){
        Log.e(缓冲区错误,错误转换结果+ e.toString());
    }    //尝试分析字符串到一个JSON对象
    尝试{
        jObj =新的JSONObject(JSON);
    }赶上(JSONException E){
        Log.e(JSON解析器,错误分析数据+ e.toString());
    }    //返回JSON字符串
    返回jObj;   }
 }


解决方案

从PHP脚本,如删除所有HTML:

 }其他{
?>
    < H1>登录和LT; / H1>
    <形式的行动=login.php中方法=后>
        用户名:其中; BR />
        <输入类型=文本名称=用户名占位符=用户名/>
        < BR />< BR />
        密码:LT; BR />
 <输入类型=密码NAME =密码占位符=密码值=/>
        < BR />< BR />
        <输入类型=提交值=登录/>
    < /表及GT;
    &所述; A HREF =register.php>寄存器&下; / A>
< PHP
}

由于JSON API应该只回声JSON数据。

另外添加以下到PHP的顶部:

 标题(内容类型:应用程序/ JSON');

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. that is the first error i am getting in the logcat could somebody tell me what the problem is. is it my php file or json code

<?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:

} 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.

Also Add the following to the top of your PHP:

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

这篇关于org.json.JSONException:值&LT; HTML&GT;&LT; HEAD&GT;&LT; java.lang.String类型风格不能转换到的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆