Hello i am currently having an issue sending a JSON object from my PHP to an Android device. I have done this before with another person and it worked fine but now it does not seem to work.
It is a simple login script. It should return the user's data or "false" based on whether the login email and password entered are correct.
The response is visible when tried in a browser but according to my colleague, he gets an empty array when viewing on his android development machine.
This is the php code:
<?php
include('config.php');
include('functions.php');
include('password_hash_lib/password.php');
if (!isset($_REQUEST["device"]))
{
$Email = $_POST['Email'];
$Password = $_POST['Password'];
try
{
if (authenticate($Email, $Password))
{
echo "true";
}
else {
echo "false";
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
else if (isset($_REQUEST["device"]))
{
$device = $_REQUEST['device'];
$Email = $_REQUEST['email'];
$Password = $_REQUEST['password'];
if ($device == 'mobi')
{
try
{
if (authenticate($Email, $Password))
{
$curruser = explode("+", $_SESSION['sess_user_auth']);
$arr = new ArrayObject(Array(), ArrayObject::STD_PROP_LIST);
$arr->userid = $curruser[0];
$arr->email = $curruser[1];
$arr->fullname = $curruser[2];
$arr->displaypic = $curruser[3];
$arr->displayname = $curruser[4];
echo str_replace("\\", "", json_encode((object) $arr));
}
else {
echo "false";
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
}
?>
This is the android code my colleague wrote:
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
boolean status=false;
LoginMgr lmgr=new LoginMgr(getSherlockActivity().getBaseContext());
try {
HttpClient httpclient= new DefaultHttpClient();
HttpGet httpget=new HttpGet("http://www.xxxxx.com/login.php?device=mobi&[email protected]&password=xxxxxxx
");
HttpResponse response= httpclient.execute(httpget);
int statuscode=response.getStatusLine().getStatusCode();
if(statuscode==200){
InputStream is=response.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
final StringBuilder stringbuild= new StringBuilder();
String curr_line;
if((curr_line=br.readLine())!=null){
stringbuild.append(curr_line);
String jsonstr=stringbuild.toString();
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getSherlockActivity(), stringbuild.toString(), Toast.LENGTH_LONG).show();
}
});
if(!jsonstr.equalsIgnoreCase("false")){
JSONObject job=new JSONObject(jsonstr);
String str=job.getString("3").replace("\\/","/");
String image="http://www.xxxxx.com/img/timthumb.php?&h=50&w=50&src=
"+str;
lmgr.loginUser(new Login(job.getString("0"),job.getString("4"),job.getString("1"),image));
status=true;
JSONObject job=new JSONObject(jsonstr);
if(job.getString("success").equalsIgnoreCase("1")){
lmgr.loginUser(new Login(job.getString("userid"),job.getString("username"),job.getString("useremail"),job.getString("userimage")));
status=true;
}
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
}
I have tried using return instead of echo in my code but that still did not work. There were no errors just an empty array.
-
Why are you removing backslashes from the json_encode?colburton– colburton2014年06月23日 14:25:28 +00:00Commented Jun 23, 2014 at 14:25
-
Because there is a url in the returned array, and the json_encode appears to add backslashes to escape certain characters.Blank EDjok– Blank EDjok2014年06月23日 14:26:52 +00:00Commented Jun 23, 2014 at 14:26
-
1But it is no longer valid json. You can't decode it anymore.colburton– colburton2014年06月23日 14:28:41 +00:00Commented Jun 23, 2014 at 14:28
-
1@blank: don't mess with JSON. You NEVER directly modify a json string, because what you're doing is introducing javascript syntax errors.Marc B– Marc B2014年06月23日 14:31:50 +00:00Commented Jun 23, 2014 at 14:31
-
Hello i tried all your suggestions but none worked for me.Blank EDjok– Blank EDjok2014年06月23日 14:39:13 +00:00Commented Jun 23, 2014 at 14:39
3 Answers 3
This should solve your problem. Try to be consistent in what your script returns. It must always returns the same kind of data (JSON) even if it fails.
<?php
include('config.php');
include('functions.php');
include('password_hash_lib/password.php');
if (!isset($_REQUEST["device"]))
{
$Email = $_POST['Email'];
$Password = $_POST['Password'];
try
{
if (authenticate($Email, $Password)) echo json_encode(array('auth' => true));
else echo json_encode(array('auth' => false));
}
catch (Exception $e)
{
echo json_encode(array('error' => $e->getMessage()));
}
}
else if (isset($_REQUEST["device"]))
{
$device = $_REQUEST['device'];
$Email = $_REQUEST['email'];
$Password = $_REQUEST['password'];
if ($device == 'mobi')
{
try
{
if (authenticate($Email, $Password))
{
$curruser = explode("+", $_SESSION['sess_user_auth']);
$json = array();
$json['userid'] = $curruser[0];
$json['email'] = $curruser[1];
$json['fullname'] = $curruser[2];
$json['displaypic'] = $curruser[3];
$json['displayname'] = $curruser[4];
echo json_encode($json);
}
else
{
echo json_encode(array('auth' => false));
}
}
catch (Exception $e)
{
echo json_encode(array('error' => $e->getMessage()));
}
}
}
EDIT: Based on your last update, you've got some mistakes in your Android code. I've tried to improve it but I haven't tested it.
@Override
protected Boolean doInBackground(Void... params)
{
boolean status = false;
LoginMgr lmgr = new LoginMgr(getSherlockActivity().getBaseContext());
try
{
// Connect to the remote server
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.xxxxx.com/login.php?device=mobi&[email protected]&password=xxxxxxx");
HttpResponse response = httpclient.execute(httpget);
int statuscode=response.getStatusLine().getStatusCode();
if(statuscode==200)
{
// Read response
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
final StringBuilder stringbuild= new StringBuilder();
String curr_line = null;
while ((curr_line = br.readLine()) != null)
{
stringbuild.append(curr_line);
}
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
Toast.makeText(getSherlockActivity(), stringbuild.toString(), Toast.LENGTH_LONG).show();
}
});
// Parse response to JSON
JSONObject json = new JSONObject( stringbuild.toString() );
if (json.has("auth"))
{
if (json.getBoolean("auth"))
{
// Authentificate with success
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
Toast.makeText(getSherlockActivity(), "Success", Toast.LENGTH_LONG).show();
}
});
}
else
{
// In this case, authentification has failed
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run()
{
Toast.makeText(getSherlockActivity(), "Wrong user credentials", Toast.LENGTH_LONG).show();
}
});
}
}
else if (json.has("userid"))
{
String userid = json.getString("userid");
String email = json.getString("email");
String fullname = json.getString("fullname");
String displaypic = json.getString("displaypic").replace("\\/","/");
String displayname = json.getString("displayname");
// In this case, we got some data about the user
String image = "http://www.xxxxx.com/img/timthumb.php?&h=50&w=50&src=" + displaypic;
lmgr.loginUser(new Login(json.getString("0"), json.getString("4"), json.getString("1"), image));
status = true;
JSONObject job = new JSONObject(jsonstr);
if(job.getString("success").equalsIgnoreCase("1"))
{
lmgr.loginUser(new Login(userid, fullname, email, displaypic));
status = true;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return status;
}
3 Comments
readLine, in your code you just read it once. Also, you were parsing the json 3 or 4 times in a row.Replace : echo str_replace("\\", "", json_encode((object) $arr));
By this : echo json_encode(array('user'=>$arr));
Comments
I had a similar issue and I changed HttpGet to HttpPost and it worked. Hope this helps