将get请求传递给android中的远程服务器

时间:2017-09-12 18:03:42

标签: php android

我正在尝试从Android应用程序向远程服务器发送帖子请求。请求应在数据库的一列中插入值。服务器端的PHP代码如下:

 <?php 
$servername="sql9.freesqldatabase.com"; 
$username="sql9193859"; 
$password="MUEpGxKWUt"; 
$dbname="sql9193859"; 
$sms_content=$_GET["sms_content"]; 

$conn=new mysqli($servername,$username,$password,$dbname); 

// check connection 

if ($conn->connect_error){
    die("Connection failed: ".$conn->connect_error); 
}
else {
    echo "connected successfully"; 
    $sql="insert into SMS_TABLE(content) values ($sms_content)"; 
    if ($conn->query($sql)===true){
        echo "New record inserted successfully"; 
    }
    else {
        echo "Error:".$sql."<br>".$conn->error; 
    }
}

?>

将get请求发送到远程服务器的方法如下:

public void insertSMS() throws IOException {
        viewbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    URL url = new URL("https://smssaver.000webhostapp.com/helloworld/insert_data.php?sms_content=100");
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.disconnect();
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });


    }

当我在浏览器上键入链接时,它正常工作。但是,当我在Android中调用它时,它无法正常工作。

1 个答案:

答案 0 :(得分:1)

openConnection

  

应该注意URLConnection instance does not establish   the actual network connection on creation. This will happen only when   calling URLConnection.connect()

您需要拨打urlConnection.connect()来执行通话

URL url = new URL("https://smssaver.000webhostapp.com/helloworld/insert_data.php?sms_content=100");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// additional attributes for request for efficiency 
urlConnection.setReadTimeout(1000);
urlConnection.setConnectTimeout(1000);
urlConnection.setRequestMethod("GET");

urlConnection.connect();