2014-02-22 95 views
0

有人可以请帮我弄清楚什么是错误我想连接我的android应用程序到mysql数据库的一个简单使用php和json登录屏幕。那是我在logcat中得到的第一个错误,可能有人告诉我问题是什么。难道是我的PHP文件或JSON代码org.json.JSONException:值<HTML><HEAD><STYLE类型的java.lang.String不能转换为JSONObject

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

代码:

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; 

    } 
} 
+1

错误您发布您传递HTML或XML以JSON对象的手段。它不知道如何解析。 –

+0

那么我需要改变什么。抱歉太天真 – user3333772

+0

服务器需要发送JSON数据,而不是html。 –

回答

0

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

因为JSON API都应该只回应JSON数据。

也将添加以下到PHP的顶部:

header('Content-type: application/json'); 
相关问题