我想注册API" http://chattymac.herokuapp.com/v1/account/register"在android中使用改造。每当新用户注册时,我们都会得到响应,因为html字符串"已成功注册"但是当现有用户注册时,我们得到json格式的响应,app崩溃,给出NULLPointerException。我的代码如下:
public interface APIService {
@Headers({"Content-Type: application/json",
"Authorization: Basic Z2VldGFuamFsaTpnZWV0YW5qYWxp"})
@POST("account/register")
Call<ResponseBody> createUser(@Body User user);
}
public class User {
private String email;
private String password;
public User(String email, String password) {
this.email = email;
this.password = password;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
}
private void userSignUp() {
//defining a progress dialog to show while signing up
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Signing Up...");
progressDialog.show();
String email = signUpEmail.getText().toString().trim();
String password = signUpPassword.getText().toString().trim();
//building retrofit object
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
//Defining retrofit api service
APIService service = retrofit.create(APIService.class);
//Defining the user object as we need to pass it with the call
User user = new User(email, password);
//defining the call
Call<ResponseBody> call = service.createUser(user);
//calling the api
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//hiding progress dialog
progressDialog.dismiss();
try {
responseMessage = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
//displaying the message from the response as toast
Toast.makeText(getApplicationContext(), responseMessage, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
由于我是android的新手,如果有人可以帮我解决如何获得字符串和json响应。提前谢谢。