I have a basic test project in Android Studio using Retrofit2 to interact with my Bluehost server.
It should send a User object to the API on the server and the API returns the User's name as a string.
Just a simple test, but the User never arrives at the API.
The log always prints MainActivity: simpleTest: onResponse: 200 empty
test.php located on the Bluehost server:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('connect.php');
$user_data = json_decode($_POST, true);
if(empty($user_data)){
mysqli_close($con);
exit(json_encode('empty')); // Return string saying 'emtpy'
}
$return_string = $user_data['name'];
echo json_encode($return_string);
mysqli_close($con);
} else {
echo json_encode('error');
}
?>
ApiInterface:
public interface ApiInterface {
// getUsers works fine, and successfully returns the users from the MySQL db on the server.
@GET( "retrofit/get_users.php")
public Call<List<User>> getUsers();
// The User should be sent to the test API as a JSON object
// But it arrives empty
@POST( "retrofit/test.php")
public Call<String> test(@Body User user);
}
The User POJO:
public class User {
Integer id; // Gson will convert Integer to null so that an auto id can be generated.
String name;
String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
In MainActivity, clicking the button sends the new User and receives the response.
simpleTest = findViewById(R.id.simpleTest);
simpleTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
User newUser = new User(name.getText().toString(), password.getText().toString());
Call<String> call = api.test(newUser);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
Toast.makeText(MainActivity.this, response.code()+": "+response.body(), Toast.LENGTH_SHORT).show();
displayProgressBar(false);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
displayProgressBar(false);
}
});
}
});