gpt4 book ai didi

java - 使用 Retrofit 将数据发布到数据库

转载 作者:可可西里 更新时间:2023-11-01 12:39:48 26 4
gpt4 key购买 nike

我在使用 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);
}

最佳答案

这个

@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 将对象附加为原始数据体

关于java - 使用 Retrofit 将数据发布到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com