我正在尝试在android上创建一个登录应用程序,我收到一个错误,告诉我JSON对象为空。
我从这里得到错误:
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
if (json == null) {
Log.e("JSON", "Object is null!!!");
}
return json;
}
这是我的JSONParser:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
for (int i=0; i<params.size(); i++) {
Log.v("askj",params.get(i).toString());
}
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.v("askj","HTTP Entity : " + convertStreamToString(httpPost.getEntity().getContent()));
}catch (Exception e){
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
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();
Log.v("askj",json);
Log.e("JSON", json);
} 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;
}
}
这就是我发送和接收的内容:
05-14 10:49:26.547 27963-28074/name.company.project V/askj﹕ tag=login
05-14 10:49:26.547 27963-28074/name.company.project V/askj﹕ email=emailTest
05-14 10:49:26.547 27963-28074/name.company.project V/askj﹕ password=passTest
05-14 10:49:26.557 27963-28074/name.company.project V/askj﹕ HTTP Entity sent : tag=login&email=emailTest&password=passTest
05-14 10:49:27.117 27963-28074/name.company.project V/askj﹕ json received: Club
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
这是我的index.php:
<?php
/**
PHP API for Login, Register, Changepassword, Resetpassword Requests and for Email Notifications.
**/
if (isset($_POST['tag']) && $_POST['tag'] != '') {
// Get tag
$tag = $_POST['tag'];
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array(
"tag" => $tag,
"success" => 0,
"error" => 0
);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'chgpass') {
$email = $_POST['email'];
$newpassword = $_POST['newpas'];
$hash = $db->hashSSHA($newpassword);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"];
$subject = "Change Password Notification";
$message = "Hello User,nnYour Password is sucessfully changed.nnRegards,nLearn2Crack Team.";
$from = "contact@learn2crack.com";
$headers = "From:" . $from;
if ($db->isUserExisted($email)) {
$user = $db->forgotPassword($email, $encrypted_password, $salt);
if ($user) {
$response["success"] = 1;
mail($email, $subject, $message, $headers);
echo json_encode($response);
} else {
$response["error"] = 1;
echo json_encode($response);
}
// user is already existed - error response
} else {
$response["error"] = 2;
$response["error_msg"] = "User not exist";
echo json_encode($response);
}
} else if ($tag == 'forpass') {
$forgotpassword = $_POST['forgotpassword'];
$randomcode = $db->random_string();
$hash = $db->hashSSHA($randomcode);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"];
$subject = "Password Recovery";
$message = "Hello User,nnYour Password is sucessfully changed. Your new Password is $randomcode . Login with your new Password and change it in the User Panel.nnRegards,nLearn2Crack Team.";
$from = "contact@learn2crack.com";
$headers = "From:" . $from;
if ($db->isUserExisted($forgotpassword)) {
$user = $db->forgotPassword($forgotpassword, $encrypted_password, $salt);
if ($user) {
$response["success"] = 1;
mail($forgotpassword, $subject, $message, $headers);
echo json_encode($response);
} else {
$response["error"] = 1;
echo json_encode($response);
}
// user is already existed - error response
} else {
$response["error"] = 2;
$response["error_msg"] = "User not exist";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$uname = $_POST['uname'];
$password = $_POST['password'];
$subject = "Registration";
$message = "Hello $fname,nnYou have sucessfully registered to our service.nnRegards,nAdmin.";
$from = "contact@learn2crack.com";
$headers = "From:" . $from;
// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else if (!$db->validEmail($email)) {
$response["error"] = 3;
$response["error_msg"] = "Invalid Email Id";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($fname, $lname, $email, $uname, $password);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
mail($email, $subject, $message, $headers);
echo json_encode($response);
} else {
// user failed to store
$response["error"] = 1;
$response["error_msg"] = "JSON Error occured in Registartion";
echo json_encode($response);
}
}
} else {
$response["error"] = 3;
$response["error_msg"] = "JSON ERROR";
echo json_encode($response);
}
} else {
echo "Club";
}
?>
我有0经验的PHP所以我不知道为什么我收到该字符串。任何帮助将不胜感激。
编辑:我不再收到“托管24分析代码...”,因为我在我的php文件末尾添加了exit;
,但行if (isset($_POST['tag']) && $_POST['tag'] != '')
仍然不正确。
如果我在index.php的开头添加此print_r($_GET);
,我会进入详细日志
Array
(
)
Club
。这是否意味着php根本没有收到任何东西?
答案 0 :(得分:0)
如果这是您收到的数据:
Club
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
然后JSON解析器不会解释它,因为它无效,您的JSON解析器将返回null (json == null)
从最底层的代码中,echo "Club";
也不是有效的JSON。我无法看到分析代码的来源,你有没有提供完整的PHP,或者你的主机注入了这个?它不应该存在,它也会阻碍JSON解析器。
答案 1 :(得分:0)
如果我添加这个print_r($ _ GET);在index.php的开头,我进去了 详细日志
您没有使用GET
POST
,因此它应该是print_r($_POST);
。
如果您不确定,请使用print_r($_REQUEST);
你也回显你的脚本我建议你按照你的方式构建你的数组,并且只在脚本结束时回显exit;
并且不要回显club
而是返回JSON
格式化的消息,以便您的Android应用在尝试解析时不会崩溃。
您在哪里定义login_tag
,if (isset($_POST['tag']))
应该足以检查是否设置了post变量。