Problem in getting values from Json response - android

I am hitting a URL with four parameters, If parameters not match I will get the Following response.
This is my JSON response:
{
"result": "0"
}
Now my question is. How do I get that result value from response?
Here's, my Retrofit instance
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static final String BASE_URL = "https://URL/";
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Retrofit Interface
public interface ApiInterface {
#GET("f/f/ff.php")
Call<Object> verifyUser (#QueryMap Map< String, String > params );
}
Code for getting the response
ApiInterface apiInterface = RetrofitClientInstance.getRetrofitInstance().create(ApiInterface.class);
Call<Object> call = apiInterface.verifyUser(params);
call.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
Log.e("Code ", response.code() + "");
if (!response.isSuccessful()) {
Log.e("Code ", response.code() + "");
return;
}
// Convert String to json object
JSONObject json = null;
String str_value = null;
try {
json = new JSONObject(String.valueOf(response));
//JSONObject json_LL = json.getJSONObject("result");
// get value from LL Json Object
str_value = json.getString("result"); //<< get value here
} catch (JSONException e) {
e.printStackTrace();
}
// Log.e("Response ", json.length() + "");
Toast.makeText(RegistrationForm.this, str_value, Toast.LENGTH_SHORT).show();
Object responseBody = response.body();
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e("Failed", t.getMessage() + "");
}
});

Since you're using Gson. You can replace Object with a class that holds the fields that you want to parse.
for example:
public class ResultResponse {
String result;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
And change your endpoint method to return this class.
public interface ApiInterface {
#GET("f/f/ff.php")
Call< ResultResponse> verifyUser (#QueryMap Map< String, String > params );
}
Also don't forget to change the remaining code to use the new return type ResultResponse
Call<ResultResponse> call = apiInterface.verifyUser(params);
call.enqueue(new Callback<ResultResponse>() {
#Override
public void onResponse(Call<ResultResponse> call, Response<ResultResponse> response) {
Log.e("Code ", response.code() + "");
if (!response.isSuccessful()) {
Log.e("Code ", response.code() + "");
return;
}
ResultResponse resultResponse = response.body();
String str_value = resultResponse.getResult();
Toast.makeText(RegistrationForm.this, str_value, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
Log.e("Failed", t.getMessage() + "");
}
});

Related

Retrofit response does not contain response data

I am hitting this API https://westus.dev.cognitive.microsoft.com/docs/services/563309b6778daf02acc0a508/operations/563309b7778daf06340c9652/console
below is my retrofit code. I am not able to send raw JSON in retrofit.
public void createProfileAPI()
{
ApiInterface apiService = ApiClient.getClientRequest().create(ApiInterface.class);
try
{
//pbVrd.setVisibility(View.VISIBLE);
JSONObject paramObject = new JSONObject();
paramObject.put("locale", "en-us");
LocaleModel localeModel = new LocaleModel();
localeModel.setLocale("en-us");
Call<BaseModel> call = apiService.SearchResponse(localeModel);
call.enqueue(new Callback<BaseModel>()
{
#Override
public void onResponse(Call<BaseModel> call, Response<BaseModel> response)
{
int responseCode = response.code();
Log.d("Deepakw" , responseCode+"");
BaseModel response1 = response.body();
Log.d("Deepak" , response.body().getIdentificationProfileId() + " //// " +response1.getIdentificationProfileId()+"");
}
#Override
public void onFailure(Call<BaseModel> call, Throwable t)
{
Log.d("Responce Failed ", "failed Response Mersen Fuse ");
String message = t.getMessage();
Log.d("failure", message);
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
public class ApiClient {
public static final String BASE_URL = "https://westus.api.cognitive.microsoft.com/spid/v1.0/";
private static Retrofit retrofit = null;
public static Retrofit getClientRequest() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
public interface ApiInterface {
#Headers({
"Content-Type: application/json",
"Ocp-Apim-Subscription-Key: 0219cf3e3d444f0584f80b3a84613d12"
})
#POST("verificationProfiles")
Call<BaseModel> SearchResponse(#Body LocaleModel body);
};
I am not able to get response
API client
Please help
//In ApiInterface do like this
#Headers("charset:UTF-8")
#POST("verificationProfiles")
Call<BaseModel> SearchResponse(
#Header("Content-Type") String contentType,
#Body LocaleModel body);
have you tried #SerializedName("") and #Expose in your pojo class
#SerializedName("status")
#Expose
private Boolean status;
Instead of JSONObject, you can use Map
For example:
Headers("Content-Type: application/json")
#POST("/apipath")
request(#Body Map<String, String> body);

how to Passing headers and body at a time in retrofit

Im sending 2 headers and a body of class type here
#POST("/api/access/change-password")
Call<JsonElement> changePassword(#Header("Content-Type") String content_type,
#Header("Authorization") String AuthToken,
#Body PostChangePassword postChangePassword);
here i am posting the data to server. but it returns some error. It is working fine in postman. but not in here.
public void postData(String old_password, String new_password) {
Log.v("im here in retro0", "");
PostChangePassword postChangePassword = new PostChangePassword(sharedPrefUserData.getUserData().getUserId(), sharedPrefUserData.getUserData().getAuthToken(), old_password, new_password);
mAPIService.changePassword("application/json", "Bearer " + sharedPrefUserData.getUserData().getAuthToken(), postChangePassword).enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
Log.v("im here in retro1", response + "");
Gson gson = new Gson();
if (response.code() == 200) {
JsonElement jsonElement = response.body();
if (jsonElement.isJsonObject()) {
JsonObject objectWhichYouNeed = jsonElement.getAsJsonObject();
ResponseChangePassword object = gson.fromJson(objectWhichYouNeed, ResponseChangePassword.class);
}
} else {
Log.v("im here in retro2", response + "");
ResponseChangePassword responseChangePassword = null;
try {
responseChangePassword = gson.fromJson(response.errorBody().string(), ResponseChangePassword.class);
Toast.makeText(ProfileActivity.this, responseChangePassword.getMessage(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
// progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
// progressBar.setVisibility(View.GONE);
internetConnectionChecker.serverErrorAlert();
Log.v("im here in retro3", "");
}
});
}

retrofit calling json data but its response show null

Here is my code any one help, why it shows response is null? There is some mistake which I cannot found.
public void getAllTasksWithSuccess(){
String url = ""+ RetrofitClient.baseURL +"here is my service code ";
RetrofitClient.createRetrofitInstance();
Call<ResponseBody> call = RetrofitClient.getCallObject("getTodaysTask",url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i("TAG",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("tag2", "Failed : " + t.getMessage());
}
});
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.ResponseBody.string()' on a null object reference
at com.ra.ra.DashboardFragments.FragmentTasks$2.onResponse(FragmentTasks.java:83)
Add below class ServiceGenerator:
public class ServiceGenerator {
public static final String API_BASE_URL = AppConstants.BASE_URL;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit retrofit = null;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static Retrofit retrofit() {
retrofit = builder.client(httpClient.build()).build();
return retrofit;
}
}
And use below ErrorUtils class to parse your response's errorBody:
public class ErrorUtils {
public static ResponseBody parseError(Response<?> response) {
Converter<ResponseBody, ResponseBody> converter =
ServiceGenerator.retrofit()
.responseBodyConverter(ResponseBody.class, new Annotation[0]);
ResponseBody error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new ResponseBody();
}
return error;
}
}
And now in your onResponse do as below:
public void getAllTasksWithSuccess(){
String url = ""+ RetrofitClient.baseURL +"here is my service code ";
RetrofitClient.createRetrofitInstance();
Call<ResponseBody> call = RetrofitClient.getCallObject("getTodaysTask",url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
// here your response.body() will not be null
}else{
// here your response.body() will be null
// and here you might get your response in response.errorBody();
ResponseBody res= ErrorUtils.parseError(response);
System.out.println("Response is:"+ res.toString());
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("tag2", "Failed : " + t.getMessage());
}
});
}

XML Parsing using Retrofit

I'm trying to make XML Response, but there is an exception.
Exception in onFailure:
org.simpleframework.xml.core.ElementException: Element 'Date' does not have a match in class
Client
public static Retrofit getXMLClient() {
if (retrofitXML == null) {
retrofitXML = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(SimpleXmlConverterFactory.create())
.build();
}
return retrofitXML;
}
Interface
#GET("odds-" + oddsAccessMode + "1"+"?")
Call<PojoOddsResponse> getOddsData(#Query("api_key") String api_key);
API call
ApiInterfaceSR apiService =
ApiClientSR.getXMLClient().create(ApiInterfaceSR.class);
Call<PojoOddsResponse> call = apiService.getOddsData(API_KEY);
call.enqueue(new Callback<PojoOddsResponse>() {
#Override
public void onResponse(Call<PojoOddsResponse> call, Response<PojoOddsResponse> response) {
if (response.body() != null && response.code() == 200) {
try {
String s = response.body().toString();
Log.d(TAG, "onResponse: "+s);
} catch (Exception e) {
Log.e("JSON exception", e.getMessage());
}
}
}
#Override
public void onFailure(Call<PojoOddsResponse> call, Throwable t) {
Log.e("api exception", t.getMessage());
}
});
Help me, please.

Retrofit 2 - string error body is empty

Server returns JSON object in case of success and simple String for error case.
There are no problems with parsing JSON into object. The problem rises when I want to parse error since the response.errorBody().string() is empty.
When I send the same request using Postman the response as follows:
And I can't read this error... Anyone faced such problem?
Code code
gradle:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp:okhttp:2.6.0'
RestClient.java:
private static GitApiInterface gitApiInterface;
...
public static GitApiInterface getClient() {
if (gitApiInterface == null) {
OkHttpClient okClient = new OkHttpClient();
okClient.interceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Retrofit client = new Retrofit.Builder()
.baseUrl(URL_BASE)
.addConverterFactory(GsonConverterFactory.create())
.build();
gitApiInterface = client.create(GitApiInterface.class);
}
return gitApiInterface;
}
ApiInterface.java:
public interface ApiInterface {
#POST("/register/user/{email}/")
Call<User> postRegisterUser(#Path(value = "email", encoded = true) String email,
#Query("firstname") String firstName,
#Query("lastname") String lastName,
#Query("country") String country,
#Query("phone") String phone,
#Query("deviceid") String deviceId);
...
ServerRequests.java:
public void registerUser(#NonNull String email,
#NonNull String firstName,
#NonNull String lastName,
#NonNull String country,
#NonNull String phone,
#NonNull String deviceId,
#NonNull final RegisterUserCallback callback) {
showProgressBar();
RestClient.GitApiInterface service = RestClient.getClient();
Call<User> call = service.postRegisterUser(email, firstName, lastName, country, phone, deviceId);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
hideProgressBar();
User user = response.body(); //this works great
if (response.isSuccess()) {
Log.d(TAG, "REGISTER success: " + response.message());
callback.onRegisteredUser(user);
} else {
try {
Log.e(TAG, "REGISTER fail: " + response.errorBody().string()); //empty error body
callback.onRegisterFailed(response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
hideProgressBar();
callback.onRegisterFailed("error");
}
});
}
My answer is based on HttpLoggingInterceptor class.
I wrote getStatusError() method by given in parameter response.errorBody().
private StatusError getStatusError(ResponseBody responseBody) {
StatusError statusError = null;
if (responseBody != null) {
try {
BufferedSource source = responseBody.source();
if (source != null) {
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
String string = buffer.clone().readString(charset);
if (!TextUtils.isEmpty(string)) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
statusError = gson.fromJson(string, StatusError.class);
}
}
} catch (Exception e) {
LogUtils.LOGW(TAG, "Impossible to get StatusError stream", e);
}
}
return statusError;
}
StatusError is a POJO class to map (JSON) elements:
public class StatusError {
#SerializedName("message")
public String message;
#SerializedName("errors")
public ArrayList<ErrorDetail> errors;
}

Categories

Resources