使用POST方法将数据从Java Android发送到Web服务器

3

我希望能够从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');
    }
?>

我在manifest文件中添加了这个权限:

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

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


你尝试在你的 PHP 文件的第一行调用 session_start() 函数来进行测试了吗? - scraaappy
你是在后台线程中进行网络操作吗?如果你在UI线程上进行网络操作,它会崩溃的。 - JRowan
请确保您正在使用 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> - Ozair Patel
@scraaappy 不,我没有叫它。 - phier
@OPatel 我已经使用过它了。 - phier
显示剩余2条评论
2个回答

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();

编辑:在开始和结束UI操作时,请使用PreExecute和OnPostExecute方法,否则您的所有视图和其他内容都将崩溃。


我试过了,它没有崩溃。但是,如果登录成功,我不知道在 PHP 中应该是什么参数。因为上面的代码是当用户在电脑上登录而不是移动设备上登录时使用的。 - phier
我对PHP一无所知,抱歉。 - JRowan
看起来你在记录日志方面走在了正确的轨道上。 - JRowan
AsyncTask可以工作,但是对于我来说有太多的仪式感。我会使用像Volley这样的库来处理网络活动。 - CrashOverride

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 是一个处理 POST 值(用户名和密码)并向应用程序发送确认的 PHP 文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接