【问题标题】:Send data from java android to webserver with post method使用 post 方法将数据从 java android 发送到网络服务器
【发布时间】:2015-02-26 04:57:05
【问题描述】:

我想将数据从 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" />

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

【问题讨论】:

  • 您是否尝试在 php 的第一行调用 session_start() 来进行测试?
  • 你是在后台线程做网络,如果你在 UI 线程上做网络会崩溃?
  • 确保您使用的是&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt;
  • @scraaappy 不,我没叫它
  • @JRowan 我在活动课上做。如何在后台线程中进行?

标签: java php android mysql send


【解决方案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 开始和结束

【讨论】:

  • 我试了一下,没有崩溃。但是,如果登录成功,我不知道php中的参数应该是什么。因为上面的代码是当用户在电脑/非手机中使用登录时。
  • 我对php一无所知,对不起
  • 看起来你的日志记录在正确的轨道上
  • AsyncTask 可以工作,但是我喜欢的仪式太多了。我会使用像 Volley 这样的库来进行网络活动。
【解决方案2】:

你需要使用 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 值(用户名和密码)并将确认发送回应用程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-14
    • 2016-10-10
    • 1970-01-01
    • 2013-10-27
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多