Я пытаюсь создать приложение для входа в android, и я получаю сообщение об ошибке, указывающее, что объект JSON имеет значение NULL.Ответ 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 -->
И это мой inde x.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 = "[email protected]";
$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 = "[email protected]";
$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 = "[email protected]";
$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";
}
?>
У меня есть опыт работы с php, поэтому я не могу сказать, почему я получаю эту строку. Любая помощь будет принята с благодарностью.
Редактировать: я больше не получаю «код аналитики 24 хостинга ...», потому что я добавил exit;
в конце моего php-файла, но строка if (isset($_POST['tag']) && $_POST['tag'] != '')
по-прежнему не соответствует действительности.
Если добавить этот print_r($_GET);
в начале index.php я получаю в журнале многословной
Array
(
)
Club
. Означает ли это, что php ничего не получает?
Тот факт, что вы «эхо» Club »;' и вы получили «Club» с сервера, говорит вам, что проблема связана с проверкой 'if ($ tag == 'login') {' Почему не вы выдаете некоторую отладочную информацию в теге $ до этого и играете с Postman? –
Как я уже сказал, у меня нет опыта работы в php. Я попробую Google, как отладить его и вернуться к вам. –
Хорошо, первое, что я хотел бы сделать, это просто добавить echo $ tag; die(); 'после' $ tag = $ _POST ['tag']; 'и проверить его, чтобы посмотреть, что делает php. –