2014-02-22 121 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'); 
相關問題