Home » Php » java – POST data to database with Retrofit

java – POST data to database with Retrofit

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am stuck into a problem with posting data to a server with Retrofit.
Here is what I try to do (and what doesn’t work):

This is the class that instances are converted and sent to the webservice:

  public class Txt {
    private String text;

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

    public String getText () {
        return text;
    }
  }

This is my Interface:

public interface textapi {

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

My Webservice:

<?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']);
?>

I don’t know what I am doing wrong. I researched and tried a lot, but I can’t get it to work :/

EDIT: Okay I got an error message on Android:

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

EDIT: I solved the problem by adding @Body in the interfeace:

 public interface textapi {

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

This

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

Should be

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

since PHP is expecting raw data, by specifying the annotation @Body in front of the object text, you are telling Java to attach the object as a raw body