0

这是我的 php 脚本,它工作正常

if (isset($_GET['username']) && isset($_GET['password'])) {
  $con = mysql_connect("localhost", "aaaa", "bbbb");
  if (!$con) {
    die('Could not connect: '.mysql_error());
  }
  mysql_select_db("login", $con);
  $u = $_GET['username'];
  $p = $_GET['password'];
  $result = mysql_query("SELECT username FROM users WHERE password = '$p' AND username = '$u' ") or die('Errant query:');
  while ($row = mysql_fetch_assoc($result)) {
    $output = $row;
  }
  print(json_encode($output));
  mysql_close($con);
} else {
  $output = "not found";
  print(json_encode($output));
}

这是我的 php 脚本返回的

{"username":"mohamed"}

这是登录活动

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    HttpResponse response = null;
    InputStream webs = null;
    BufferedReader br = null;
    String line = "";
    String result = "";
    String url = "http://localhost/login.php?username=";
    EditText user = (EditText) findViewById(R.id.editText1);
    EditText pass = (EditText) findViewById(R.id.editText2);
    url = url + user.getText().toString() + "&password=" + pass.getText().toString();
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    try {
      response = httpClient.execute(httpPost);
      HttpEntity entity = response.getEntity();
      webs = entity.getContent();
      br = new BufferedReader(new InputStreamReader(webs, "iso-8859-1"), 8);
      StringBuilder sb = new StringBuilder();
      while ((line = br.readLine()) != null) {
        sb.append(line + "\n");
      }
      webs.close();
      result = sb.toString();
    } catch (ClientProtocolException e1) {
      e1.printStackTrace();
    } catch (IllegalStateException e1) {
      e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    final String res = result;
    Button lgn = (Button) findViewById(R.id.button1);
    lgn.setOnClickListener(new View.OnClickListener() {
      public void onClick(View arg0) {
        try {
          JSONObject json = new JSONObject(res);
          if (json.getString("username").equals("mohamed")) {
            Toast t = Toast.makeText(getApplicationContext(), "logged in", Toast.LENGTH_LONG);
            t.show();
          } else {
            Toast t = Toast.makeText(getApplicationContext(), "Invalid User", Toast.LENGTH_LONG);
            t.show();
          }
        } catch (JSONException e) {
          Toast t = Toast.makeText(getApplicationContext(), "Error Reading username", Toast.LENGTH_LONG);
          t.show();
          e.printStackTrace();
        }
      }
    });
  }
}

Toast 出现“读取用户名错误”

有明确的互联网许可

安卓 4.2.2

4

2 回答 2

0

只需删除\nfrom while 循环,无需将其编辑为中断行,只需按原样读取即可。

StringBuilder sb=new StringBuilder();
while ((line=br.readLine())!=null) {
      sb.append(line);
}

这将更改您的 json,\n并且当您解析它时,这将引发异常,因为它不是有效的形式。根据您在编辑后的回复\n将得到

{"username":"mohamed"}\n // so here this will invalid json format
于 2013-04-13T10:38:15.970 回答
0

这是我如何处理 php 和 json 的示例,希望对您有所帮助:

php:

 $result=mysql_query("SELECT * FROM MyTable ");

 $info=array();

 while($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {

      array_push($info,$row);
    }

 echo json_encode($info);

安卓:

网络服务部分:

 JSONArray jsonArray;
 HttpClient httpclient = new DefaultHttpClient();
 String url = "http://myurl.com/myphpfile.php";
 HttpGet getRequest = new HttpGet(url);

 try {
    HttpResponse response = httpclient.execute(getRequest);
    final String str = EntityUtils.toString(response.getEntity());

    jsonArray = new JSONArray(str);




} catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
} catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
}

解码json部分:

 JSONObject jsonObject;
 String id,user,pswd;
 try{
for (int i = 0; i < jsonArray.length(); i++) {
    jsonObject = jsonArray.getJSONObject(i);

     id = jsonObject.getString("ID");
     user = jsonObject.getString("username");
    pswd = jsonObject.getString("password");

}

 }catch(Exception e){

        }

笔记:

== 直接使用 webservices 会导致 4.0 手机出错,你必须使用异步任务,将 web services 部分放在 doinbackground 部分。==您可以更改代码以匹配您的表格字段,您需要的网络服务方法(发布或获取)......

于 2013-04-13T11:34:38.710 回答