【发布时间】: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