I'm studying android, and I'm trying to use the retrofit library with android. After reading the documentation and seeing several examples in answers here in stackoverflow I was able to send data from a form via POST
to a page written in php and receive the return (in JSON
format), however I can not receive all the objects , I get only the first one, I can get all the data if I use GET
, but not if I use POST
, someone would know if this is possible using POST
, in case I get several objects, GET
, follow my code below:
Dependencies:
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
MainActivity (within a button):
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.101.36/json/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService apiService = retrofit.create(ApiService.class);
Call<User> call = apiService.validateUser(inputEmail.getText().toString(), inputSenha.getText().toString());
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
//Verifica se houve a conexão com sucesso ao webservice
if (!response.isSuccessful()) {
textView.setText("ERROR onResponde: " + response.code());
} else {
//requisição retona os dados com sucesso
String email = response.body().getEmail();
String senha = response.body().getPassword();
textView.append("email: " + email + " - senha: " + senha + "\n");
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
t.printStackTrace();
textView.setText(t.getMessage());
}
});
Interface:
public interface ApiService {
@FormUrlEncoded
@POST("index.php")
Call<User> validateUser(
@Field("username") String username,
@Field("password") String password
);
}
User class:
public class User {
private int id;
private String error, error_msg, username, email, password;
public String getError(){
return this.error;
}
public String getError_msg(){
return this.error_msg;
}
public int getId(){
return this.id;
}
public String getUsername(){
return this.username;
}
public String getPassword(){
return this.password;
}
public String getEmail(){
return this.email;
}
}
Index.php:
$email = $_POST['username'];
$senha = $_POST['password'];
echo '
{
"email":"'.$email.'",
"password":"'.$senha.'"
},
{
"email":"'.$email.'",
"password":"'.$senha.'"
},
{
"email":"[email protected]",
"password":"123456"
}
';