使用post方法将数据从java android发送到webserver

时间:2014-12-30 01:30:51

标签: java php android mysql send

我想将数据从Java Android发送到mysql php服务器。

这是按钮点击的代码:

public void loginPost(View view){
      String username = usernameField.getText().toString();
      String password = passwordField.getText().toString();
      String result="";

      HttpClient httpclient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
      try {
          List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("UserName", username));
          nameValuePairs.add(new BasicNameValuePair("PassWord", password));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

          HttpResponse response = httpclient.execute(httppost);
          HttpEntity entity = response.getEntity();

          if (entity != null) {
              StringBuilder sb = new StringBuilder();
              String line;
              InputStream instream = entity.getContent();
              BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
              while ((line = bf.readLine()) != null ) {
                  sb.append(line).append("\n");
              }
              result = sb.toString();
              Log.i("Read from server", result);
          }

      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      status.setText(username);

      //Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
      //startActivity(intent);
}

这是我在login.php中的代码:

<?php 
    include("connect.php");

    //define $myusername and $mypassword
    $myusername = $_POST['UserName'];
    $mypassword = $_POST['PassWord'];

    //to protect mysql injection
    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);
    $myusername = mysql_real_escape_string($myusername);
    $mypassword = mysql_real_escape_string($mypassword);

    $mypassword = $mypassword;

    $sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
    echo $sql;
    $result = mysql_query($sql);    


    //mysql_num_row is counting table row
    $count = mysql_num_rows($result);
            echo "<script> alert('".$count."')</script>";

    if($count == 1)
    {
        session_start();
        $row = mysql_fetch_array($result);
        //$_SESSION['login'] = $myusername;
        $_SESSION['id_member'] = $row['id_member'];

            header('Location: login.php');
    }
    else
    {
        header('Location: default.php');
    }
?>

我在清单中添加了此权限:

<uses-permission android:name="android.permission.INTERNET" />

但运行后应用程序停止了。我不知道错误在哪里。

2 个答案:

答案 0 :(得分:1)

尝试在ASyncTask中建立网络,这样你的网络就不会在UIThread上完成,我想这就是为什么你的崩溃

类似这样的事情

class TheTask extends AsyncTask<Void,Void,Void>
{



      protected void onPreExecute()
      {           super.onPreExecute();

      } 

       protected Void doInBackground(Void ...params)
      {  


       loginPost();//View view); // View view replace
                             // i think even having view as a parameter will crash 
                             // doinbackground method you have to change it i think

      } 

       protected void onPostExecute(Void result)
      {     

                super.onPostExecute(result);

                    // Back to UIThread, i think handle status.setText(username);
                    // from here and take it out of your loginPost() method UI operations will 
                    // crash doInBackground(Void ...params)


      } 
}

然后在你的代码中调用它

new TheTask().execute();

编辑:你的所有观点和诸如此类的东西都会在PreExecute和OnpostExecute上使用doinbackground方法来开始和结束UIOperations

答案 1 :(得分:0)

您需要使用AsyncTask。

        public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
             protected String doInBackground(ArrayList<String>... userdata) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.website.com/script.php");

                String result = null;
                try{
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
                    nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);
                    InputStream is = response.getEntity().getContent();
                    String line = "";
                    StringBuilder total = new StringBuilder();

                    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                    while ((line = rd.readLine()) != null) { 
                        total.append(line); 
                    }
                    result = total.toString();
                }
                catch(NoHttpResponseException e){
                    Log.d("resultLoginError", e.getMessage());
                }
                catch(Exception e){
                    Log.d("resultLoginOther", e.toString());
                }
                return result;
             }
             @Override
            protected void onPreExecute() {
            super.onPreExecute();
            }
             protected void onPostExecute(String result) {
                 Log.d("resultOnLogin", "LOGGED?");
                 }
         }

    public String Login(String user, String pass) throws InterruptedException, ExecutionException{
        ArrayList<String> userdata = new ArrayList<String>();
        userdata.add(user);
        userdata.add(pass);

        return new UserLogin().execute(userdata).get();
    }

这是我个人用来登录的。

script.php是一个PHP文件,用于处理POST值(用户名和密码)并向应用程序发回确认。