【问题标题】:Sending string to php server将字符串发送到 php 服务器
【发布时间】:2014-10-04 00:37:02
【问题描述】:

我正在尝试从应用程序向 php 服务器发送一个字符串,应该发送该字符串(该方法执行时没有错误),但服务器没有收到任何内容。 这就是我正在做的事情,我关注了另一个 SO 线程,所以我真的不知道我正在做的事情是否正确。

    protected String doInBackground(String... params) {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);

        try {
            StringEntity se = new StringEntity(data);
            httppost.setEntity(se);
            httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return null;
    }

这是在网络应用程序中将数据发送到服务器的代码。

     function send_message( message ) {
        data =  "data";
        $.ajax({
          type: 'POST',
          url:"url",
          data: data,
          success: function() {
            $("#message_sent").val( "true" );
          },
          error: function(json) {
          },
          abort: function( json ) {
          }
        });
      }

所以基本上我想将发送数据的js代码翻译成java代码并在应用程序中使用。

【问题讨论】:

  • data 是一个对象,需要像 data = {"str":"data"}
  • @kellycode 数据在 js 代码和我的 java 代码中都是一个字符串,我只是将它存储为一个变量。
  • 为了对所有神圣事物的热爱,请不要让你的捕获为空,至少做一些 Log.e(),否则你永远不会知道是否出了问题。跨度>
  • @AlvarezAriel 我还是个菜鸟,请多多包涵:)
  • 这一切都是出于好意。现在您知道,将 catch 留空通常是一种倒退做法,为了您自己的利益,您应该至少添加一些日志记录。可能这就是我们需要弄清楚这段代码出了什么问题的全部内容。使用developer.android.com/tools/debugging/debugging-log.html

标签: java javascript php android


【解决方案1】:

这是发送方法的一个简单示例:

function send_message(message) {
            var data = {"data":message};
            $.ajax({
                type: 'POST',
                url: "ret.php",
                data: data,
                success: function(returned) {
                    console.log(returned);
                },
                error: function(json) {
                     console.log(json);
                },
                abort: function(json) {
                }
            });
        }

还有一个简单的 php 示例,该文件位于与 html 页面相同的目录中名为 ret.php 的文件中:

<?php
$info = $_POST["data"];
echo $info;

你的成功方法会得到回声

你可以用一个按钮来调用它:

<button type="button" onclick="send_message('my message');"> Send it</button>

【讨论】:

  • 这不是用户要求的,他想让他的代码在android上运行,在java中。 php中的示例只是为了向我们展示他正在尝试做的事情。
猜你喜欢
  • 2016-02-10
  • 1970-01-01
  • 2014-07-19
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
相关资源
最近更新 更多