Android:从java发送数据到一个php文件并有回应

我正在编写一个android应用程序,我有一个登录活动,用户必须插入一个用户名和密码,因此我需要将我的应用程序与我的数据库连接起来,以检查用户是否被注册。

我在Altervista上创建了一个mysql数据库,并且还创建了一个执行查询的php文件。 这是login.php的代码:

<?php

$UserName =$_POST['name'];
$Password =$_POST['pass'];

$hostname="localhost";
$user="myuser";
$pass="mypass";


$conn=mysql_connect($hostname,$user,$pass);
if(!$conn){
    echo("Error");
}

$db=mysql_select_db('my_finditdatabase');
if(!$db)
{
    echo "db non presente o mancata selezione";
}

$query="SELECT UserName,Password FROM Utente WHERE UserName='$UserName' AND Password='$Password';";

$ris=mysql_query($query);
$cont=0;
$riga=mysql_fetch_array($ris);
while($riga)
{
    print(json_encode("Exist"));
    $cont++;
    $riga=mysql_fetch_array($ris);
}

if($cont==0){
    print(json_encode("NoExist"));
    echo mysql_error();
}
mysql_close();
?>

我需要连接到URL,从Java发送用户名和密码的值

$UserName =$_POST['name'];
$Password =$_POST['pass'];

然后从PHP文件接收打印'Exist'或'NoExist'。

print(json_encode("Exist"));

print(json_encode("NoExist"));

我已经尝试从互联网的代码,他们给了我很多不赞成的方法,如:DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest =新的HttpPost(URL);
StringEntity se; se = new StringEntity(jsonObjSend.toString());
和别的...

我能怎么做 ? 请帮助我,因为我真的需要它。 谢谢


晚上好Jay,首先让我们构建JSON并发送给服务器,在Android APP中创建一个AsyncTask或其他一些异步服务来执行Web连接。

然后按以下示例进行操作:

 HttpURLConnection urlConnection = null; // Will do the connection
 BufferedReader reader;                  // Will receive the data from web
 String strJsonOut;                      // JSON to send to server
 Uri buildUri = Uri.parse("http://url.com.br").buildUpon().build(); // build the uri
//inside a try to prevent errors
try {
            URL url = new URL(buildUri.toString().trim());

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(0);
            urlConnection.setConnectTimeout(1500); // timeout of connection
            urlConnection.setRequestProperty("Content-Type", "application/json"); // what format will you send
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true); // will receive
            urlConnection.setDoOutput(true); // will send
            urlConnection.connect();
            Stream outputStream = urlConnection.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(outputStream);
            JSONObject objLogin = new JSONObject();
            objLogin.put("pass",passVariable);
            objLogin.put("name",nameVariable);
            ow.write(objLogin.toString());
ow.close();

//information sent by server
 InputStream inputStream = urlConnection.getInputStream();
                   StringBuffer buffer = new StringBuffer();
                   if (inputStream == null) {

                     // response is empty, do someting
                       return null;
                   }
 reader = new BufferedReader(new InputStreamReader(inputStream));
 String strJsonServer = buffer.toString();
 objServerResponse = new JSONObject(strJsonServer);
boolean status = objServerResponse.getBoolean("status");

return status; // Your response, do what you want.

}catch (JSONException e, IOException er)
                       {
                           // error on the conversion or connection
                       }

在服务器上,只需使用状态键创建一个数组。

$name = $_POST['name'];
$pass = $_POST['pass'];

// do your logical


$response = array();
if(true){
$response['status'] = 'true';
}
else{
$response['status']= 'false';
}

echo json_encode($response,JSON_UNESCAPED_UNICODE); // Second parameter to correct special characters to UTF-8

我无法在此刻测试此解决方案,如果出现错误,请检查我的语法是否正确,并防止catch子句出现可能的错误。

链接地址: http://www.djcxy.com/p/29593.html

上一篇: Android:Send data from java to a php file and have a response

下一篇: Which Collection should I convert in JSON and parse again?