【问题标题】:How get list of objects with post request to retrofit 2.1.0 with android如何获取带有发布请求的对象列表以使用 android 改造 2.1.0
【发布时间】:2017-02-05 02:10:38
【问题描述】:

我是 Android 编程和 Retrofit 的新手。

我看到许多改进库的示例,发出GET 请求,传递参数并将所有对象放在PHP 的页面上。 有可能,对POST 做同样的事情吗? 我想从我的webservice 中获取所有数据(JSON 对象),通过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;
}
}

索引.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"
  }
  ';
}

如果我在应用程序中使用对象数组发生错误:

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

【问题讨论】:

    标签: php android post request retrofit


    【解决方案1】:

    如果您期望多次返回,则需要指定您的调用返回一个列表。

       @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() 会给你一个用户对象列表,你可以遍历。

    【讨论】:

    • 本,亲爱的,非常非常感谢!它工作 100%,这周很痛苦。
    【解决方案2】:

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

            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());
                        }
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 2019-06-14
      • 2018-09-01
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多