Get Retrofit Response as String
There are two ways:
Out of the box Retrofit supports using OkHttp's
ResponseBody
type.ResponseBody
is basically an abstraction on "just bytes" and has a method calledstring()
which will consume the body as aString
.You can add the
converters-scalars
artifact and add theScalarsConverterFactory
to your instance which will allow usingString
as your response type.
how to Access to the Response body in the retrofit?
Finally, with these changes, I was able to reach a conclusion.
ApiSeviceClass
public void getVerifyCode(String mobile, RequestStatus requestStatus) {
Log.i(TAG, "getVerifyCode: Called");
HashMap<String, String> map = new HashMap<>();
map.put("command", "register_user");
map.put("mobile", mobile);
Log.i(TAG, "getVerifyCode: requestCode: " + map.toString());
retrofitApi.callBack(map).enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
if (response.isSuccessful()) {
String strResponseBody = response.body().string();
Log.i(TAG, "getVerifyCode:onResponse: " + strResponseBody);
requestStatus.onSuccess(strResponseBody);
}
} catch (IOException e) {
Log.e(TAG, "onResponse: " + e.getMessage());
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "getVerifyCode:onFailure= " + t.getMessage());
requestStatus.onError(new Exception(t));
}
});
}
Retrofit Callback
@POST(".")
Call<ResponseBody> callBack(@QueryMap Map<String, String> map);
Retrofit 2: Get JSON from Response body
Use this link to convert your JSON into POJO with select options as selected in image below
You will get a POJO class for your response like this
public class Result {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("Username")
@Expose
private String username;
@SerializedName("Level")
@Expose
private String level;
/**
*
* @return
* The id
*/
public Integer getId() {
return id;
}
/**
*
* @param id
* The id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return
* The username
*/
public String getUsername() {
return username;
}
/**
*
* @param username
* The Username
*/
public void setUsername(String username) {
this.username = username;
}
/**
*
* @return
* The level
*/
public String getLevel() {
return level;
}
/**
*
* @param level
* The Level
*/
public void setLevel(String level) {
this.level = level;
}
}
and use interface like this:
@FormUrlEncoded
@POST("/api/level")
Call<Result> checkLevel(@Field("id") int id);
and call like this:
Call<Result> call = api.checkLevel(1);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
if(response.isSuccessful()){
response.body(); // have your all data
int id =response.body().getId();
String userName = response.body().getUsername();
String level = response.body().getLevel();
}else Toast.makeText(context,response.errorBody().string(),Toast.LENGTH_SHORT).show(); // this will tell you why your api doesnt work most of time
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(context,t.toString(),Toast.LENGTH_SHORT).show(); // ALL NETWORK ERROR HERE
}
});
and use dependencies in Gradle
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.+'
NOTE: The error occurs because you changed your JSON into POJO (by use of addConverterFactory(GsonConverterFactory.create())
in retrofit). If you want response in JSON then remove the addConverterFactory(GsonConverterFactory.create())
from Retrofit. If not then use the above solution
Unable to get data using retrofit library
you bind a wrong model calss so you just need to change and also Your base url needs to end with "/"
RestResponse
To
RestResponseMain
API client
public class ApiClient {
public final String baseUrl="http://services.groupkt.com/";
public static Retrofit retrofit;
public static Retrofit getData() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
in API Interface and MainActivty.show below
API interface
public interface ApiInterface {
@GET("country/get/all")
Call<RestResponseMain> getData();
}
MainActivity
ApiInterface apiInterface = ApiClient.getData().create(ApiInterface.class);
Call<RestResponseMain> call = apiInterface.getData();
pDialog.show();
call.enqueue(new Callback<RestResponseMain>() {
@Override
public void onResponse(Call<RestResponseMain> call, Response<RestResponseMain> response) {
pDialog.dismiss();
List<Result> list = response.body().getResult();
MyRecyclerRetrofitAdapter adapter = new MyRecyclerRetrofitAdapter(MainActivity.this,list);
rView.setAdapter(adapter);
}
@Override
public void onFailure(Call<RestResponseMain> call, Throwable t) {
}
});
How to get the value with GSON / Retrofit?
1 Create your model class
public class ResponseItem {
/**
* code : 200
* lang : en-ms
* text : ["Burung"]
*/
private int code;
private String lang;
private List<String> text;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public List<String> getText() {
return text;
}
public void setText(List<String> text) {
this.text = text;
}
}
2 inside your Retrofit method response :
if (response.isSuccessful()) {
ResponseItem responseItem;
responseItem = response.body(); }
and you can call text by saying responseitem.Get("whatever u want from the model class")
Related Topics
How to Get Name of Wifi-Network Out of Android Using Android API
Cancel Notification on Remove Application from Multitask Panel
Mediarecorder and Videosource.Surface, Stop Failed: -1007 (A Serious Android Bug)
Sms Authentication on Android Nullpointerexception
Run Code When Android App Is Closed/Sent to Background
Flutter Projects & Android X Migration Issues
Android: Retrieve Contact Name from Phone Number
Appcompatactivity.Oncreate Can Only Be Called from Within the Same Library Group
How to Set the Divider Between Tabs in Tablayout of Design Support Library
Phonegap/Cordova Android Development
How to Get Screen Coordinates from Marker in Google Maps V2 Android
Answer Incoming Call Using Android.Telecom and Incallservice
Supporting Multiple Screen Size - Android
Custom Cut/Copy Action Bar for Edittext That Shows Text Selection Handles
How to Maintain the Immersive Mode in Dialogs
Android - Switch Actionbar Back Button to Navigation Button
How to Get the Android Path String to a File on Assets Folder