【问题标题】:Android send string to PHPAndroid将字符串发送到PHP
【发布时间】:2016-05-13 10:39:36
【问题描述】:

我正在尝试使用 php 将 android 与 mysql 连接起来,以便将参数包含到表中。

我制作了有效的 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);
        };
    }
...

服务器请求

> 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";
}

 ?>

【问题讨论】:

  • 你可以在write参数到OutputStream之后尝试conn.connect()

标签: php android mysql


【解决方案1】:

使用 Volley 库。很简单。

样本:Volley Library

你也可以找到my answer

【讨论】:

  • 嗨@Sathish。我尝试复制您的答案的代码,但在我的情况下,对话框说我:“JSON 错误”、“服务器错误..!一段时间后尝试..!”
  • 请根据您的需要进行修改。检查您的网址是否有效
  • 好的,我收到相同的对话框,但在 mysql 中创建了该行。代码执行 php 文件,但不传递参数。使用 $_POST 或使用 $_GET,我一无所获。请查看我的编辑帖子
  • 好的,我找到了我的问题但没有解决方案:stackoverflow.com/questions/37212109/…
【解决方案2】:

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" />

【讨论】:

  • 我试试你的代码。当单击按钮时,logcat 中仅显示此消息:sendUserActionEvent() mView == null,屏幕中显示一个空吐司。
  • 你在休息控制中检查你的反应吗?
  • 我在那里检查过,我在 html 代码响应那里得到错误
  • & 顺便说一下 sendUserActionEvent() mView == null 在那里没有任何问题。您可以参考stackoverflow.com/questions/18028666/… 进行确认...。我一直使用此代码,效果很好。 ........首先,您必须在任何其他客户端中检查您的响应...就像 PostMan ..
  • 问题出在我的...服务器上?其他?看到这个帖子stackoverflow.com/questions/37212109/…
【解决方案3】:

我可以看到的问题是您没有保留从服务器返回的响应。您正在返回 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;
}

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多