【问题标题】:POST data to database with Retrofit使用 Retrofit 将数据发布到数据库
【发布时间】:2015-08-04 04:40:56
【问题描述】:

我在使用 Retrofit 将数据发布到服务器时遇到问题。 这是我尝试做的(以及不起作用的):

这是实例被转换并发送到网络服务的类:

  public class Txt {
    private String text;

    public Txt (String text) {
        this.text = text;
    }

    public String getText () {
        return text;
    }
  }

这是我的界面:

public interface textapi {

  @POST("/php/set_string.php")
  public void setText (Txt text, Callback<String> cb);
}

我的网络服务:

<?php
$user = "user";
$database = "db";
$password = "pw";

$data = json_decode(file_get_contents("php://input"), true);

$con = mysqli_connect("localhost", $user, $password, $databse);

$statement = mysqli_prepare ($con, "INSERT INTO votes (vote_text) VALUES (?)");
mysqli_stmt_bind_param ($statment, "s", $data['text']);
mysqli_stmt_execute($statement);

mysqli_close($statment);
mysqli_close($con);

header('Content-Type: application/json');
echo json_encode($data['text']);
?>

我不知道我做错了什么。我研究并尝试了很多,但我无法让它工作:/

编辑:好的,我在 Android 上收到一条错误消息:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true)

编辑:我通过在界面中添加@Body 解决了这个问题:

 public interface textapi {

  @POST("/php/set_string.php")
  public void setText (@Body Txt text, Callback<String> cb);
}

【问题讨论】:

  • 究竟是什么不工作?你有任何错误吗?
  • 问题是我没有得到任何错误,它只是不工作:/
  • 您是否尝试过显示所有 PHP 错误?将其放在页面顶部:error_reporting(E_ALL); ini_set('display_errors', '1');
  • 感谢您的帮助波诺 :)
  • 这(部分)解决了吗?如果你不介意的话,我会把它作为答案发布:)

标签: java php retrofit


【解决方案1】:

这个

@POST("/php/set_string.php")
public void setText (Txt text, Callback<String> cb);

应该是

@POST("/php/set_string.php")
public void setText (@Body Txt text, Callback<String> cb);

由于 PHP 需要原始数据,通过在对象文本前面指定注释 @Body,您是在告诉 Java 将对象作为原始正文附加

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多