Android将字符串发送给PHP

时间:2016-05-13 10:39:36

标签: php android mysql

我尝试使用php将android与mysql连接起来,将params包含在表格中。

我制作了有效的PHP代码。但是我不明白为什么不能使用android的代码。我没有在logcat中收到错误。

MainActivity:

...
boton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sendMessage("mensaje");
            }
        });
    }


    public void sendMessage(String t){

        ServerRequests serverRequests = new ServerRequests(this);
        serverRequests.fetchUserDataAsyncTask(t);{
            Log.d("", "sendMessage: "+t);
        };
    }
...

ServerRequest

> public class ServerRequests {
> 
>     URL url;
>     HttpURLConnection conn;
>     ProgressDialog progressDialog;
>     String mensaje;
> 
>     public ServerRequests(Context context) {
>         progressDialog = new ProgressDialog(context);
>         progressDialog.setCancelable(false);
>         progressDialog.setTitle("Authenticating...");
>         progressDialog.setMessage("Please wait...");
>     }
> 
>     public void fetchUserDataAsyncTask(String mensaje) {
>         progressDialog.show();
>         new fetchUserDataAsyncTask(mensaje,"hola").execute();
>     }
> 
>     public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, String> {
> 
>         String returnedUser;
> 
> 
>         public fetchUserDataAsyncTask(String mensaje, String returnedUser) {
> 
>         }
> 
>         @Override
>         protected String doInBackground(Void... params) {
> 
>             try {
> 
>                 url = new URL("http://gclimb.com/androidphp/index.php");
> 
>                 conn = (HttpURLConnection) url.openConnection();
>                 String param = "mensaje="+mensaje;
>                 conn.setRequestMethod("POST");
>                 conn.setDoInput(true);
>                 conn.setDoOutput(true);
>                 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
>                 conn.setRequestProperty("charset", "UTF-8");
>                 conn.connect();
> 
>                 OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
>                 out.write(param);
> 
>                 //No code to receive response yet, want to get the POST working first.
> 
>             }
>             catch (MalformedURLException e) {
>                 e.printStackTrace();
>             } catch (ProtocolException e) {
>                 e.printStackTrace();
>             } catch (IOException e) {
>                 e.printStackTrace();
>             }
>             catch (Exception e) {
> 
>             } finally {
>                 progressDialog.dismiss();
>             }
> 
>             return returnedUser;
>         }
>     }
> 
> }

修改

这是简单的index.php文件。

php文件:

<?php

$mensaje = $_POST['username'];
$mensaje2 = $_POST['password'];
$bo = $mensaje;
$servername = "zzzzzzz";
$username = "zzzzzz";
$password = "zzzzz";
$dbname = "zzzzz";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO AndroidPhp (mensaje) VALUES ('$bo')";
$conn->query($sql);





$sql2="SELECT mensaje FROM AndroidPhp";

$result = $conn->query($sql2);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      echo $row["mensaje"];
    }
} else {
    echo "0 results";
}

 ?>

3 个答案:

答案 0 :(得分:0)

使用Volley Library。这很简单。

  

样品:Volley Library

您也可以找到my answer

答案 1 :(得分:0)

WsHttpPost.java

public class WSHttpPost extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
Context context;
HttpURLConnection httpConnection;
ContentValues values;
public WSHttpPost(Context context, ContentValues values) {
    // TODO Auto-generated constructor stub
    this.context = context;
    this.values = values;
}

@Override
protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    pDialog = new ProgressDialog(context);
    pDialog.setTitle("Connecting...");
    pDialog.setMessage("Please Wait...");
    pDialog.setCancelable(false);
    pDialog.show();
}

@Override
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub
    String result = "";
    try {
        URL url = new URL(params[0]);
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestProperty("Accept", "application/json");
        //httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConnection.setReadTimeout(10000);
        httpConnection.setConnectTimeout(15000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(String.valueOf(values));
        writer.flush();
        writer.close();
        os.close();

        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream iStream = httpConnection.getInputStream();
            InputStreamReader isReader = new InputStreamReader(iStream);
            BufferedReader br = new BufferedReader(isReader);
            String line;
            while ((line = br.readLine()) != null) {
                result += line;
            }
        }
    } catch (java.net.SocketTimeoutException e) {
        Toast.makeText(context, "Network Error : No Data Received.", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Log.e("Error : ", e.toString());
    }
    return result;
}

@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    pDialog.dismiss();
    try {
        Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
      }
   }
}

调用

boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues cv = new ContentValues();
            cv.put("mensaje",mensaje);
            WsHttpPost httpPost = new WsHttpPost(MainActivity.this,cv);
            httpPost.execute("http://gclimb.com/androidphp/index.php");
          }
       });
   }
  

并且不要忘记在Manifest.xml中添加权限

<uses-permission android:name="android.permission.INTERNET" />

答案 2 :(得分:0)

我可以看到的问题是你没有持有从服务器返回的响应。您正在返回returnedUser,但是您检查了此变量包含的内容吗?

您可以看到以下方法,或者您可以使用任何库与服务器进行通信。

您可以为此使用RetroFit或Volley。

请参阅以下示例:

http://www.truiton.com/2015/04/android-retrofit-tutorial/

http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

public String executePost(String targetURL, String urlParameters) {
    URL url;
    HttpURLConnection connection = null;
    StringBuffer response = new StringBuffer();
    try {
        // Create connection

        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(urlParameters.getBytes().length));

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);


        // Send request
        DataOutputStream wr = new DataOutputStream(
                connection.getOutputStream());
        wr.writeBytes(urlParameters);

        wr.flush();
        wr.close();

        // Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;

        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        //Log.v("JSON ", " " + response.toString());
        return response.toString();

    } catch (SocketTimeoutException ex) {
        ex.printStackTrace();

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
        //  Log.v("JSON ", " " + response.toString());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        //  Log.v("JSON ", " " + response.toString());
    } catch (IOException ex) {

        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (Exception e) {
        e.printStackTrace();
        //   Log.v("JSON ", " " + response.toString());
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}