您好我目前在将PHP的JSON对象发送到Android设备时遇到问题。 我之前和另一个人做过这件事并且工作正常,但现在它似乎没有用。
这是一个简单的登录脚本。它应该根据输入的登录电子邮件和密码是否正确返回用户的数据或“false”。
在浏览器中尝试时,响应是可见的,但据我的同事说,在他的Android开发机器上查看时,他得到一个空数组。
这是php代码:
<?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();
}
}
}
?>
这是我的同事写的安卓码:
@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=xxxxxx@gmail.com&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;
}
我在我的代码中尝试使用return而不是echo,但仍然无效。只有一个空数组没有错误。
答案 0 :(得分:1)
这应该可以解决您的问题。尝试在脚本返回的内容中保持一致。它必须始终返回相同类型的数据(JSON
),即使它失败了。
<?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()));
}
}
}
修改强> 根据您的上次更新,您的Android代码中存在一些错误。我试图改进它,但我还没有测试过它。
@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=xxxxxx@gmail.com&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;
}
答案 1 :(得分:0)
替换:echo str_replace("\\", "", json_encode((object) $arr));
由此:echo json_encode(array('user'=>$arr));
答案 2 :(得分:0)
我有一个类似的问题,我将HttpGet更改为HttpPost并且它有效。希望这有帮助