dongqian3198 2012-11-19 17:18
浏览 60
已采纳

将POST数据从Android应用程序发送到PHP脚本

I'm trying to send some POST data to a PHP script from an android application. How should the PHP script look like? This is what I tried but it doesn't work;

Android code:

class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.alex26.0fees.net/script.php");

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("id", "12345"));
            nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

PHP script:

<?php
if(isset($_POST['id']))
    echo $_POST['id'];
if(isset($_POST['stringdata']))
    echo $_POST['stringdata'];
?>
  • 写回答

1条回答 默认 最新

  • dpwgzi7987 2012-11-19 17:27
    关注

    Anything sent via POST to PHP script ends in $_POST array. What the script will do with it is another question. Simplest test, that writes content of $_POST to a file named "myfile.txt" (note each request would overwrite content of the file):

    <?php
    
        file_put_contents("myfile.txt", print_r( $_POST, true ));
    
    ?>
    

    echoing in your script is pointless - you are not consuming server response nor displaying it so how could it "work"?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作