使用JSON登录表单

时间:2013-08-22 16:41:27

标签: java android json login jsonobject

我正在尝试通过连接到我的数据库并验证用户名和密码来创建登录表单,我正在使用JSON方法

 public class LoginActivity extends Activity {
 JSONParser jParser = new JSONParser();
 private static String url_login = "http://192.168.1.81:80get_all_usernames.php";
 JSONArray admin = null;
 int i;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.adminlogin);
}


 public void enter(View v)
 {

      TextView user= (TextView) findViewById (R.id.user);
      TextView pass= (TextView) findViewById (R.id.pass);
      CharSequence usr=  user.getText();
      CharSequence pwd=pass.getText();
      Log.i("",""+usr);
      Log.i("",""+pwd);
      ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
     JSONObject json = jParser.makeHttpRequest(url_login, "GET",param);

      Log.i("","fjefejjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj");
     try{
       int success = json.getInt("success");

       if(success == 1){
    admin = json.getJSONArray("admin");
        for(i=0;i<admin.length();i++){
        final JSONObject c = admin.getJSONObject(i);
        String real_user=c.getString("username");
        String real_password= c.getString("password");
            if(usr==real_user && pwd==real_password)
            {
     Log.i("success","login sucessfull-----------------------");
        }
     else{
       Log.i("fail","Login failed ----------------------------------");
         }
     }}
    }catch(Exception e){
      }
   }

      }

它一直在该行返回错误: JSONObject json = jParser.makeHttpRequest(url_login,“GET”,param); 有人可以帮我吗?

提前谢谢你, 拉尔夫

2 个答案:

答案 0 :(得分:1)

您的网址错误:

http://192.168.1.81:80get_all_usernames.php

应该是:

http://192.168.1.81:80/get_all_usernames.php

此外,对于http,您不需要指定端口80.这是默认设置。

答案 1 :(得分:1)

首先纠正您的网址然后 使用HttpClient和AsynsTask进行网络请求。

public final class HttpTask extends  AsyncTask<Strin param, Void param, String param> {

private HttpClient mHc = new DefaultHttpClient();

@Override
protected String doInBackground(String... params) {

   HttpClient client = new DefaultHttpClient();
   HttpPost request = new Http(params[0]);
   try
   {
       // Add params using Name Value Pair

       HttpResponse response = client.execute(request);
       HttpEntity entity = response.getEntity();
       InputStream inputStream = entity.getContent();
       //Parse Response from InputStream  
   }

   // return  "Success" or "fail";
}

@Override
protected void onProgressUpdate(Boolean... progress) {


}

@Override
protected void onPostExecute(String result) {

}

}