0

如何将数据发送到下面的这个 PHP 文件?我可以建立连接并发送数据,但无法收到响应。我需要发送 3 个参数,“op”、用户名和密码。

switch ($_POST["op"]) {

    // User Authentication.
    case 1:
        $UName = $_POST["UName"];
        $UPass = $_POST["UPass"];
        $UPass = md5($UPass);

        //....Some code

    // New user registration process.
    case 2:
        $UName = $_POST["UName"];
        $UPass = $_POST["UPass"];
        $UEmail = $_POST["UEmail"];
        $UNick = $_POST["UNick"];
        $UPass = md5($UPass);

         //....Some code
        }

到目前为止我的代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://SomeUrl/login.php");

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("1", "dan"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            response = httpclient.execute(httppost);
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.d(TAG, ""+responseBody);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

我究竟做错了什么?

4

2 回答 2

1

Android HTTP POST 应该如下所示:

     HttpParams httpParams=new BasicHttpParams();
     HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
     HttpConnectionParams.setSoTimeout(httpParams, 10000);

     // Data to send
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
     nameValuePairs.add(new BasicNameValuePair("UPass", "password"));
     nameValuePairs.add(new BasicNameValuePair("op", "1"));

     //http post
     try{
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost("http://SomeUrl/login.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();

     }catch(Exception e){

     }

在您的 PHP 代码中,我强烈建议使用 mysql_real_escape_string($_POST['U​​Name']) 否则很容易通过 SQL 注入进行攻击。我还建议使用 SSL 连接 (HTTPS) 或仅发送散列密码 (MD5)

于 2012-12-30T14:29:12.870 回答
1

查看您的 PHP 代码,您至少需要指定一个op参数。然后根据您尝试执行的操作,确保您还指定了其他需要的参数。对于用户身份验证(op = 1):

nameValuePairs.add(new BasicNameValuePair("op", "1"));
nameValuePairs.add(new BasicNameValuePair("UName", "dan"));
nameValuePairs.add(new BasicNameValuePair("Pass", "somepass"));

附带说明,如果您使用 SSL 来处理敏感的用户信息,您应该使用 SSL 保护 PHP 服务。

于 2012-12-30T14:38:16.653 回答