我遇到了使用Retrofit将数据发布到服务器的问题。 这是我尝试做的(以及什么不起作用):
这是实例转换并发送到Web服务的类:
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)
编辑:我通过在interfeace中添加@Body解决了这个问题:
public interface textapi {
@POST("/php/set_string.php")
public void setText (@Body Txt text, Callback<String> cb);
}
答案 0 :(得分:0)
此
@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将对象附加为原始主体