如何获取具有post请求的对象列表以使用android改进2.1.0

时间:2016-09-27 12:30:12

标签: php android post request retrofit

我是Android编程新手并使用Retrofit。

我看到很多示例来改进库,发出GET个请求,传递参数并将所有对象放在PHP的页面上。 有可能,对POST做同样的事情吗? 我想从我的JSON中提取所有数据(webservice对象),并通过POST传递参数,但我无法执行。

有没有人做过或有过帮助我的例子?

在stackoverflow中学习文档并查看示例,我可以在下面做例子,但只返回第一个对象。

依赖关系:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

MainActivity(按钮内):

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 + " - password: " + senha + "\n");
            }
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            t.printStackTrace();
            textView.setText(t.getMessage());
        }

    });

接口:

public interface ApiService {
   @FormUrlEncoded
   @POST("index.php") 
   Call<User> validateUser(
        @Field("username") String username,
        @Field("password") String password
   );
}

班级用户:

public class User {
private String  username, email, password;

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

if ($email == "manoelps@live.com") {

  echo '
  {
    "email":"' . $email . '",
    "password":"' . $senha . '"
  },
  {
    "email":"myemail@live.com",
    "password":"654321"
  },
  {
    "email":"joselito@joselito.com",
    "password":"123456"
  }
  ';

} else {

  echo '
  {
    "email":"otheremail@otheremail.com",
    "password":"987654"
  },
  {
    "email":"otheremail@otheremail.com",
    "password":"987654"
  },
  {
    "email":"otheremail@otheremail.com",
    "password":"987654"
  }
  ';
}

如果我在app中使用了对象数组错误:

[{
"email":"manoelps@live.com",
"password":"123456"
},
{
"email":"manoelps@live.com",
"password":"123456"
}]

2 个答案:

答案 0 :(得分:0)

如果您希望多次返回,则需要指定您的呼叫返回列表。

   @FormUrlEncoded
   @POST("index.php") 
   Call<User> validateUser(
        @Field("username") String username,
        @Field("password") String password
   );

应该是

   @FormUrlEncoded
   @POST("index.php") 
   Call<List<User>> validateUser(
        @Field("username") String username,
        @Field("password") String password
   );

然后在你的回调中response.body()会给你一个你可以迭代的用户对象列表。

答案 1 :(得分:0)

为了将来的参考,对于那些需要它的人,我的回调如下:

        Call<List<User>> call = apiService.validateUser(inputEmail.getText().toString(), inputSenha.getText().toString());
        call.enqueue(new Callback<java.util.List<User>>() {
            @Override
            public void onResponse(Call<List<User>> call, Response<List<User>> response) {
                //Verifica se houve a conexão com sucesso ao webservice
                if (!response.isSuccessful()) {
                    textView.setText("ERROR onResponde: " + response.code());
                } else {

                    try {

                        //pegando os dados
                        List<User> listUsers = response.body();

                        //retona os dados
                        for (User c : listUsers) {
                            textView.append("Email: " + c.getEmail() + " - " + "Senha: " + c.getPassword() + "\n");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        textView.setText("ERROR:" + e.getMessage());
                    }
                }
            }