请在gradle中使用这些。
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
使用这两个POJO类........
LoginData.class
public class LoginData {
private String email;
private String password;
public LoginData(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
LoginResult.class
public class LoginResult {
private Boolean error;
private String message;
private Integer doctorid;
private Boolean active;
public Boolean getError() {
return error;
}
public void setError(Boolean error) {
this.error = error;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Integer getDoctorid() {
return doctorid;
}
public void setDoctorid(Integer doctorid) {
this.doctorid = doctorid;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
像这样使用API
public interface RetrofitInterface {
@POST("User/DoctorLogin")
Call<LoginResult> getStringScalar(@Body LoginData body);
}
使用如下方式调用...
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("Your domain URL here")
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface service = retrofit.create(RetrofitInterface .class);
Call<LoginResult> call=service.getStringScalar(new LoginData(email,password));
call.enqueue(new Callback<LoginResult>() {
@Override
public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
}
@Override
public void onFailure(Call<LoginResult> call, Throwable t) {
}
});
编辑:
将此放置在 success()
中....
if(response.body().getError()){
Toast.makeText(getBaseContext(),response.body().getMessage(),Toast.LENGTH_SHORT).show();
}else {
//response.body() have your LoginResult fields and methods (example you have to access error then try like this response.body().getError() )
String msg = response.body().getMessage();
int docId = response.body().getDoctorid();
boolean error = response.body().getError();
boolean activie = response.body().getActive()();
}
注意:始终使用POJO类,可以消除Retrofit中的JSON数据解析。
@Field
而不是@Body
。或者将您的请求转换为POJO,然后使用@Body
发送。 - sushildlhRequestBody
->RequestBody body = RequestBody.create(MediaType.parse("text/plain"), text);
详细答案请参考 https://futurestud.io/tutorials/retrofit-2-how-to-send-plain-text-request-body - Kidus Tekeste