android:使用HttpURLConnection

时间:2015-10-09 19:15:33

标签: java php android

我搜索了很多,但所有问题都是关于如何发送HTTP请求或接收响应。

我的问题是,当我发送数据时,每次都会得到相同的结果,就像没有发布数据一样。

我将我的php文件设置为返回“无效请求”,如果没有发布数据,您将看到

我的java代码是:

TextView result;
private Handler handler;
String serverUrl = "https://daiilydeal.com/soft.php";

String action = "login";
String userName = "myusername";
String password = "mypassword";
String charset = "UTF-8";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    result = (TextView) findViewById(R.id.txSms);
    handler = new Handler();

        String encodrdQuery = String.format("action=%s&username=%s&password=%s",
                URLEncoder.encode(action, charset),
                URLEncoder.encode(userName, charset),
                URLEncoder.encode(password, charset));

        String query = "action=" + action + "&username=" + 
     userName + "&password=" + password;

        performPost(encodrdQuery );
        performPost(query); 
}

 public void performPost(final String encodedData) {
    result.setText(encodedData); // here I'm getting action=login&username=myusername&password=mypassword
    new Thread(new Runnable() {
        public void run() {
            HttpURLConnection connection ;
            DataOutputStream request = null;
            BufferedReader in = null;
            final String response;
            try {
                URL url = new URL(serverUrl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestProperty("charset", "utf-8");
                request  = new DataOutputStream(connection.getOutputStream());
                // perform POST operation
                request.writeBytes(encodedData);
                request.flush();
                request.close();
                String line = "";
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                response = sb.toString();
                        Log.d("Debug",response);                        
                    in.close();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (request != null) {
                    try {
                        request.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

这是我的php文件,它在C#程序中运行得很好

$host = 'localhost';
$db = 'soft';
$user = 'soft';
$pass = 'mm';
mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_query("SET NAMES 'utf8' ");
$action = $_POST['action'];
if ($action == 'login') 
{ 
    $UserName = $_POST['username'];
    $Password = $_POST['password'];
        if ( $UserName != null && $Password != null ) 
        {
            $q = mysql_query("select * from agents where username = '$UserName' and password = '$Password' ");
                if (mysql_num_rows($q) != 0 ) 
                {
                    $data = mysql_fetch_row($q);
                    // in case the login information is correct
                    //I return a column that indicates if the user is panned or not
                    echo $data[3]; 
                }   
                else 
                {
                    echo "Invalid User or Pass";
                }
        }
}
else if ($action == 'save') 
{
    $phone = $_POST['phone'];
    $pass = $_POST['password'];
    $id = $_POST['identity'];
    $user = $_POST['username'];
    $numex = mysql_query("select * from tbCard where phone = '$phone'"); //    Check if the number is in the DB
    if (mysql_num_rows($numex )!= Null)
    {
            echo 'this number has been registered before';
            die();
    }
    $q = mysql_query(" INSERT INTO tbCard(phone,password,identity,username) VALUES ('$phone','$pass','$id','$user')");
    if (!$q)
    {
    die(mysql_error());
    }
    else {
    echo 'Success';
    }
}
else 
{
    echo 'Invalid Request';
}
?>

但结果总是“无效请求” 没有POST数据发送到php文件。

代码有什么问题? 我在stackoverflow中尝试了很多解决方案,但都有相同的结果!

0 个答案:

没有答案