【问题标题】:HttpRequest with JAVA (libGdx) and processing it with PHP使用 JAVA (libGdx) 的 HttpRequest 并使用 PHP 处理它
【发布时间】:2014-03-31 19:34:01
【问题描述】:

我真的可以在这里使用一些帮助。 我正在使用 libGDX 学习 HttpRequest,但我坚持使用 setContent(); 这是我正在尝试运行的 Java 代码。它工作正常,除了一个小问题:它不会将变量“name”和“score”发送到 httptest.php 文件。但是 php 文件运行正常,将空值插入数据库。 Eclipse 甚至以空名称和 0 分向我显示成功的结果:

Status code : 200
Result : connected succesfully inserted and his score: 0

所以看起来这两个程序可以通信,除了 java 没有将数据发送到 php。 我的想法用完了,不知道该怎么办。

java代码:

 Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("name", "testname1");
        parameters.put("score", "56");
       HttpRequest request = new HttpRequest(HttpMethods.POST);
       request.setUrl("www.myurl.com/httptest.php");

       request.setContent(HttpParametersUtils.convertHttpParameters(parameters));
    //   request.setContent("name=testname&score=10");

       Gdx.net.sendHttpRequest(request, new HttpResponseListener() {
               @Override
               public void handleHttpResponse(HttpResponse httpResponse) {
                       Gdx.app.log("Status code ", "" + httpResponse.getStatus().getStatusCode());
                       Gdx.app.log("Result ", httpResponse.getResultAsString());
               }
               @Override
               public void failed(Throwable t) {
                       Gdx.app.log("Failed ", t.getMessage());
               }
       });

php代码:

<?php
$name=$_POST["name"];
$scoreget=$_POST["score"];
$score=(int)$scoreget;
if (is_int ($score))
{
// Create connection
$con=mysqli_connect($mycon);

// Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
  else{echo"connected ";}

$sql= "INSERT INTO scores (name, score, text) VALUES ('$name', '$score','')";
if (!mysqli_query($con, $sql))
    {
    die('Error: ' . mysqli_error($con));
    }else{
    echo "succesfully inserted ".$name." and his score: ".$score;
        }
}else{
echo "Invalid numeric type";
}   
?>

我还用这个表单测试了 httptest.php,它工作正常:

<html> 
<body>
<form action="httptest.php" method="post">
Name: <input type="text" name="name"><br>
Score: <input type="text" name="score"><br>
<input type="submit">
</form>
</body>
</html>

【问题讨论】:

  • 在 Java 代码中有一行注释掉了。它适用于那条线吗?
  • 很遗憾没有。那是我的第一次尝试,我是从网上找到的示例文件中复制的,我不明白为什么它不起作用...
  • file_get_contents('php://input'); 有什么回报吗?
  • 我不知道应该在哪里插入:file_get_contents('php://input');
  • file_get_contents('php://input'); 返回一个字符串,将其插入您的 php 脚本并回显结果。

标签: java php post libgdx httprequest


【解决方案1】:

如果您在请求中正确设置 Content-Type 标头会有帮助吗?

request.setHeader("Content-Type", "application/x-www-form-urlencoded");

我想知道除非存在正确的内容类型,否则 PHP 是否不将 POST 正文中的参数分开。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    相关资源
    最近更新 更多