【问题标题】:Sending string data to PHP file on server: string is not sent?将字符串数据发送到服务器上的 PHP 文件:未发送字符串?
【发布时间】:2016-02-10 15:14:39
【问题描述】:

我正在尝试使用POST 和`GET 将string 发送到远程服务器上的PHP 文件,然后PHP 将字符串写入文本文件。

我的代码(如下)编译并运行没有错误,但是当按下提交按钮时,没有操作。 IE。 toast 不显示,当我检查从服务器上的 PHP 文件写入的 text file 时,什么都没有。

我是否遗漏了一些非常明显会导致它不起作用的东西? (注意:“my_url”是故意存在的,这不是错误)

Android 代码:

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.tvTitle)
    TextView title;
    @Bind(R.id.etName)
    EditText name;
    @Bind(R.id.etEmail)
    EditText email;
    @Bind(R.id.etIdea)
    EditText idea;
    @Bind(R.id.btnSubmit)
    Button submit;

    String toSubmit = "";
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

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

        submit.setOnClickListener(new Button.OnClickListener() {
                    public void onClick(View v) {

                      try{
                            new MyTask().execute();
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                });
    }

    public static long copyLarge(InputStream input, OutputStream output)
            throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        if (count > Integer.MAX_VALUE) {
            return -1;
        }
        return (int) count;
    }

    private class MyTask extends AsyncTask<String, Void, String>
    {
        boolean success = false;

        @Override
        protected String doInBackground(String... params) {

            StringBuilder respData = new StringBuilder();
            InputStream stream = null;
            OutputStream os = null;
            HttpURLConnection httpUrlConnection;
            URLConnection conn;
            URL url;

            try {

                url = new URL("my_url/recieveString.php");
                conn = url.openConnection();
                httpUrlConnection = (HttpURLConnection) conn;

                httpUrlConnection.setUseCaches(false);
                //httpUrlConnection.setRequestProperty("User-Agent", "App");
                httpUrlConnection.setConnectTimeout(30000);
                httpUrlConnection.setReadTimeout(30000);
                httpUrlConnection.setRequestMethod("POST");
                httpUrlConnection.setDoOutput(true);
                os = httpUrlConnection.getOutputStream();

                toSubmit = "test";

                stream = new ByteArrayInputStream(toSubmit.getBytes(StandardCharsets.UTF_8));

                copy(stream, os);

                httpUrlConnection.connect();

                int responseCode = httpUrlConnection.getResponseCode();

                if (200 == responseCode) {
                    InputStream is = httpUrlConnection.getInputStream();
                    InputStreamReader isr = null;
                    try {
                        isr = new InputStreamReader(is);
                        char[] buffer = new char[1024];
                        int len;
                        while ((len = isr.read(buffer)) != -1) {
                            respData.append(buffer, 0, len);
                        }
                    } finally {
                        if (isr != null) {
                            isr.close();
                            success = true;
                        }
                    }
                    is.close();
                } else {
                    // use below to get error stream
                    //inputStream = httpUrlConnection.getErrorStream();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                stream.close();
                os.flush();

                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                return "done";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Toast toast = Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT);

        }
    }

}

PHP 文件:

<?php 

$stringRecieved=$_GET["toSubmit"]; 

$file = 'list.txt';

// Write the contents to the file, 
file_put_contents($file, $stringRecieved, FILE_APPEND | LOCK_EX);
?>

【问题讨论】:

  • 虽然您可以混合使用 GET 和 POST,但您似乎不太可能这样做。根据 android 代码,您似乎正在使用 POST,因此您需要在 php 中访问 $_POST
  • 你试过用调试器单步调试吗? isr 请求后有什么值吗?
  • 不,我在请求后看不到它的值?
  • 你能看出代码还有什么问题吗?
  • 你能看出代码还有什么问题吗?

标签: php android post android-asynctask get


【解决方案1】:

如果您要 POST 到服务器,该变量将不在 GET 中。

$stringRecieved = $_POST["toSubmit"];

顺便说一句,提供一个包装器并测试 POST 是否实际被使用通常是一个好主意;清理输入通常是个好主意,并且确保访问来自有效来源通常是个好主意,而您的 PHP 似乎还没有这样做。

【讨论】:

  • 为什么不包括空格以提高可读性? $stringRecieved = $_POST["toSubmit"];
  • 因为我从他的代码中剪切并粘贴了它,而不是匆忙。固定的。 :-)
  • 您好,谢谢,我已经更改了 php 文件,但仍然无法正常工作。你能在 android 代码中看到错误吗?抱歉,我是初学者,这是我对任何期望非常基本的应用程序的第一次体验!
  • 这里没有 Droid 编程经验。为什么这被注释掉了? ''' //inputStream = httpUrlConnection.getErrorStream(); ''' 我想你想知道在这个阶段是否有任何错误。
猜你喜欢
  • 1970-01-01
  • 2014-07-19
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多