REST API call always onFailure - android

I am new to Android rest api, basically I was trying to retrieve some information from a demo website using rest api together with the retrofit. Somehow my api call always on failure, hope someone could help.
Api.class
String BASE_URL = "https://demo.openmrs.org/openmrs/ws/rest/v1/";
#GET("location?tag=Login%20Location")
Call<List<RetroLocation>> getLocation();
Location.class
#SerializedName("display")
#Expose
protected String display;
#Expose
private String name;
public RetroLocation() {}
public RetroLocation(String display) {
this.display = display;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
Call the api from the main class
private void retriveLocation() {
//create object for the RetrofitInstance
RestApi api = RetrofitInstance.getRetrofitInstance().create(RestApi.class);
//making the call object using the api method created in the api class
Call<List<RetroLocation>> call = api.getLocation();
//making the call using enqueue(), it takes callback interface as an argument
call.enqueue(new Callback<List<RetroLocation>>() {
#Override
public void onResponse(Call<List<RetroLocation>> call, Response<List<RetroLocation>> response) {
progressDoalog.dismiss();
if (response.body() != null) {
//goes to my list
List<RetroLocation> locationList = response.body();
//creating an string array for the listview
String[] location = new String[locationList.size()];
//fill in the array with the response data from json
for (int i = 0; i < locationList.size(); i++) {
location[i] = locationList.get(i).getName();
}
//displaying the string array into the listView
ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_row, R.id.location, location);
listviewLocation.setAdapter(adapter);
Log.d("result", "Respond");
//generateDataList(response.body());
}else
Log.d("result", "No response");
}
#Override
public void onFailure(Call<List<RetroLocation>> call, Throwable t) {
//if(progressDoalog != null && progressDoalog.isShowing())
//progressDoalog.dismiss();
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
Log.d("result", "onFailuer");
}
});
RestInstance.class
public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(RestApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
}
if(retrofit!=null)
Log.d("result", "logged in");
return retrofit;
}
static OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Authorization", "Basic "+ getAuth())
.header("Accept", "application/json")
.method(original.method(),original.body())
.build();
return chain.proceed(request);
}
}).build();
Update: Here is the throwable error message
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
at retrofit2.ServiceMethod.toResponse(ServiceMethod.java:119)
at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:218)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:112)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
The output of base_url
<org.openmrs.module.webservices.rest.SimpleObject serialization="custom">
<unserializable-parents/>
<map>
<default>
<loadFactor>0.75</loadFactor>
<threshold>12</threshold>
</default>
<int>16</int>
<int>3</int>
<string>uuid</string>
<string>b1a8b05e-3542-4037-bbd3-998ee9c40574</string>
<string>display</string>
<string>Inpatient Ward</string>
<string>links</string>
<list>
<org.openmrs.module.webservices.rest.web.Hyperlink>
<rel>self</rel>
<uri>
http://demo.openmrs.org/openmrs/ws/rest/v1/location/b1a8b05e-3542-4037-bbd3-998ee9c40574
</uri>
</org.openmrs.module.webservices.rest.web.Hyperlink>
</list>
</map>
<linked-hash-map>
<default>
<accessOrder>false</accessOrder>
</default>
</linked-hash-map>
</org.openmrs.module.webservices.rest.SimpleObject>
<org.openmrs.module.webservices.rest.SimpleObject serialization="custom">
<unserializable-parents/>
<map>
<default>
<loadFactor>0.75</loadFactor>
<threshold>12</threshold>
</default>
<int>16</int>
<int>3</int>
<string>uuid</string>
<string>2131aff8-2e2a-480a-b7ab-4ac53250262b</string>
<string>display</string>
<string>Isolation Ward</string>
<string>links</string>
<list>
<org.openmrs.module.webservices.rest.web.Hyperlink>
<rel>self</rel>
<uri>
http://demo.openmrs.org/openmrs/ws/rest/v1/location/2131aff8-2e2a-480a-b7ab-4ac53250262b
</uri>
</org.openmrs.module.webservices.rest.web.Hyperlink>
</list>
</map>
<linked-hash-map>
<default>
<accessOrder>false</accessOrder>
</default>
</linked-hash-map>
</org.openmrs.module.webservices.rest.SimpleObject>

try this
BASE URL https://demo.openmrs.org/
Retrofit Interface
#GET("openmrs/ws/rest/v1/location")
Call<List<RetroLocation>> getLocation(#Query("tag") String tag);

Change like this may work.
String BASE_URL = "https://demo.openmrs.org/";
#GET("openmrs/ws/rest/v1/location?tag=Login%20Location")
Call<List<RetroLocation>> getLocation();

Related

Getting error while fetching an API through Retrofit , but same API is working with postman

This is the error we are facing
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 1119 path $.data[4].last_received_message
public void DeviceList(String api, final ApiType apiTypes, String page_no, String authtoken) {
ProgressDialog progressDialog = new ProgressDialog();
try {
this.pdLoading = progressDialog.getInstance(this.context);
this.pdLoading.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
if (this.pdLoading.isShowing()) {
this.pdLoading.cancel();
}
this.pdLoading.show();
} catch (Exception e) {
e.printStackTrace();
}
this.apiTypeVariable = apiTypes;
/*RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(api) //Setting the Root URL
.build();*/
Retrofit retrofit = new Retrofit.Builder().baseUrl(api).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
GitApi gi = retrofit.create(GitApi.class);
call = (Call<T>) gi.getDevices(authtoken, page_no);
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
t = (T) response.body();
if (pdLoading.isShowing())
pdLoading.cancel();
onResponseListner.onResponse(t, apiTypeVariable, true);
}
#Override
public void onFailure(Call<T> call, Throwable t) {
Log.e(apiTypes.toString(), t.getMessage() + ".");
if (pdLoading.isShowing())
pdLoading.cancel();
onResponseListner.onResponse(null, apiTypeVariable, false);
}
});
}```
It tells that there is a problem occurred when convert json string to your model. Specifically, one of your model's properties is declared as String type but there is a field (key) of the json string maps to an object type. Please check the compatible of your model and the result you received from api

Rapid API Error code 500 with Retrofit2 Android

I am using spoonacular API for a recipe app project. The problem occurs when trying to making multiple GET requests to the API. The first request is a simple search with a query parameter. The resulting JSON of the first request contains a Recipe ID and I use that ID to make the second GET request , where the problem occurs.
The API responds only when I make the request the first time but after that it responds with error code 500 [Internal Server Error].
I have tested the GET request on Postman but there it works fine every time.
I'm new to working with API's and any help would be immensely appreciated.
This is my Retrofit Service Class
public class ServiceGenerator {
public static final String API_BASE_URL = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass, final String HostName, final String KeyVal)
{
if (!TextUtils.isEmpty(HostName) && !TextUtils.isEmpty(KeyVal))
{
HeadersInterceptor interceptor = new HeadersInterceptor(HostName,KeyVal);
if (!httpClient.interceptors().contains(interceptor))
{
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
This is the Interceptor I am using to add Headers with the request.
public class HeadersInterceptor implements Interceptor {
private String HostName,KeyVal;
HeadersInterceptor(final String HostName,final String KeyVal) {
this.HostName = HostName;
this.KeyVal = KeyVal;
}
#NotNull
#Override
public Response intercept(#NotNull Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder()
.addHeader("X-RapidAPI-Host",HostName)
.addHeader("X-RapidAPI-Key",KeyVal);
Request request = builder.build();
return chain.proceed(request);
}
}
This is my Fragment which makes a search query and SUCCESSFULLY return results[Receipe ID's]
public class ListSelectedFragments extends Fragment {
private ProgressBar PreviewFragPrg;
private final String TAG = "ListSelectedFragment->";
private PreviewRecipeAdapter adapter;
private RecyclerView SelectedItemRV;
private ArrayList<RecipePreviewHolder> RecipePreviewsList = new ArrayList<>();
public ListSelectedFragments() {
// Required empty public constructor
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_list_selected_fragments, container, false);
SelectedItemRV = view.findViewById(R.id.SelectedItemRV);
TextView DisplayNameTV = view.findViewById(R.id.DisplayNameTV);
PreviewFragPrg = view.findViewById(R.id.PreviewFragPrg);
ImageView BackBtn = view.findViewById(R.id.BackBtn);
BackBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getFragmentManager() != null) {
getFragmentManager().popBackStackImmediate();
}
}
});
if (getArguments() != null) {
final String QueryTag = getArguments().getString("QueryTag");
final String CuisineName = getArguments().getString("CuisineName");
if(CuisineName!=null){
DisplayNameTV.setText(CuisineName);
}
if(QueryTag!=null){
ProcessQuery(QueryTag);
}
}
return view;
}
private void ProcessQuery(final String QueryStr){
String hostname = getResources().getString(R.string.spoonacular_host_name);
String key = getResources().getString(R.string.spoonacular_apikey_val);
final ServiceGenerator.GetDataService mService =
ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);
Call<RecipeInfoModel> call = mService.getRecipes(QueryStr);
call.enqueue(new Callback<RecipeInfoModel>() {
#Override
public void onResponse(#NonNull Call<RecipeInfoModel> call,
#NonNull Response<RecipeInfoModel> response)
{
Log.d(TAG, "Request Response Received");
Log.d(TAG, response.toString());
if (response.body() != null) {
Results[] mRES = response.body().getResults();
SetUpRecipePreviews(mRES);
PreviewFragPrg.setVisibility(View.GONE);
}
}
#Override
public void onFailure(#NonNull Call<RecipeInfoModel> call, #NonNull Throwable t) {
Log.d(TAG, "Request Failed");
Log.d(TAG, call.toString());
Log.d(TAG, "Throwable ->" + t);
PreviewFragPrg.setVisibility(View.GONE);
Toast.makeText(getActivity(),"Could not get required recipes",Toast.LENGTH_SHORT).show();
}
});
Log.d(TAG, "User Inputed Request\n"+call.request().url().toString());
}
private void SetUpRecipePreviews(final Results[] mRES) {
RecipePreviewsList.clear();
adapter = new PreviewRecipeAdapter(getActivity(),RecipePreviewsList);
SelectedItemRV.setLayoutManager(new GridLayoutManager(getActivity(), 2));
SelectedItemRV.setAdapter(adapter);
for (Results mRE : mRES) {
String ImgUrls = mRE.getImage();
RecipePreviewHolder obj = new RecipePreviewHolder(Integer.valueOf(mRE.getId()),
mRE.getTitle(), ImgUrls);
Log.d("GlideLogs->","Rid->"+mRE.getId());
Log.d("GlideLogs->","Img URL->"+ ImgUrls);
Log.d("GlideLogs->","Name->"+mRE.getTitle());
RecipePreviewsList.add(obj);
}
if(RecipePreviewsList.size()>1){
adapter.notifyDataSetChanged();
}
}
This is the Activity I transition to from my Fragment after clicking on a Recipe Card... Sending the Recipe ID in the extras. This function is called immediately after receiving intent extras.
private void RetrieveRecipeInfo(final int recipeID) {
String hostname = getResources().getString(R.string.spoonacular_host_name);
String key = getResources().getString(R.string.spoonacular_apikey_val);
final ServiceGenerator.GetDataService mService =
ServiceGenerator.createService(ServiceGenerator.GetDataService.class, hostname,key);
Call<RecipeDetailedInfo> call = mService.getInformation(185071);
Log.d(TAG , "Your GET Request:\n"+call.request().url().toString());
call.enqueue(new Callback<RecipeDetailedInfo>() {
#Override
public void onResponse(#NonNull Call<RecipeDetailedInfo> call, #NonNull Response<RecipeDetailedInfo> response)
{
Log.d(TAG,"OnResponse() Called\n");
Log.d(TAG,"Response = "+ response);
if(response.body()!=null) {
String obj = response.body().getSourceUrl();
Log.d(TAG,"Getting Recipe Info\n");
Log.d(TAG, String.valueOf(obj));
}
}
#Override
public void onFailure(#NonNull Call<RecipeDetailedInfo> call, #NonNull Throwable t){
}
});
}
Using postman I get the results every time but in my application the API stops responding after the first request. Is there a problem with the way I'm including headers?
So I finally got things working. The problem was with the HeadersInterceptor.java. I was using the Interceptor to add the Headers with the call but I found out a much easier way and it works like a charm.
Simply add #Header with the call to add headers without interceptor in Retrofit.
public interface GetDataService {
#GET("recipes/complexSearch?")
Call<RecipeInfoModel> getRecipes(
#Header("X-RapidAPI-Host") String api,
#Header("X-RapidAPI-Key") String apiKey,
#Query("query") String query_str);
}

Getting Unauthorized response inspite of sending correct authorization details

I am using Twilio Rest API for sending wireless commands using the android studio.
I have implemented the code structure according to their documentation for wireless commands. but when I hit the button to get the response, instead of getting the desired result I am getting Unauthorized 401 response. I am using their API for the first time, so clearly not having an idea, what I am doing wrong here.
Here is my code for this:
public void byApi() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiRetro.BASE_URL)
.build();
here SIMSID is the unique anme for the twilio sim card and the command i am sending is hello machine!
Credentials credentials=new Credentials(SIMSID,COMMAND);
ApiRetro apiRetro = retrofit.create(ApiRetro.class);
Call<ResponseBody> call = apiRetro.getSid(credentials);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful())
{
try {
String hyyy=response.body().string();
try {
JSONObject jsonObject=new JSONObject(hyyy);
String test=jsonObject.getString("status");
Log.v("sdfg",test);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.v("TAG",response.body().string());
Toast.makeText(getApplicationContext(),response.body().string(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),response.code()+" "+response.message(),Toast.LENGTH_LONG).show();
Log.v("one", String.valueOf(response.errorBody()));
Log.v("two",response.message());
Log.v("three", String.valueOf(response.code()));
Log.v("four", String.valueOf(response.headers()));
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.getStackTrace();
}
});
}
The interface for the Retrofit request looks like this:
String BASE_URL = "https://wireless.twilio.com/v1/";
#Headers({"AccountSid:yyyyyyyyyyyyyyyyyxxxx",
"AuthToken: yyyyyyyyyyyyyyyyyyyyxxx",
"token: ",
"Content-Type: application/x-www-form-urlencoded"})
#POST("Commands")
Call<ResponseBody> getSid(#Body Credentials credentials);
Body class:
public class Credentials {
String Sim;
String Command;
public Credentials(String sim, String command) {
Sim = sim;
Command = command;
}
public String getSim() {
return Sim;
}
public void setSim(String sim) {
Sim = sim;
}
public String getCommand() {
return Command;
}
public void setCommand(String command) {
Command = command;
}
}
OK ,i solved it .The issue was in the request where i was not sending according to the requirements.
by adding interceptor solved my problem
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new BasicInterceptor(SID,AUTH))
.build();
and then just
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.baseUrl(ApiRetro.BASE_URL)
.build();
and removing the headers from the interface like
#POST("Commands")
#FormUrlEncoded
Call<ResponseBody> getSid(#Field("Sim") String sim,#Field("Command") String command);

Android i get NULL when i post data with Retrofit

I'm novice on using Retrofit, I want to post data as an json data with object format to server and get response from that, I tested my restful url with fake data and that work fine without any problem, but when i post data from android i get null. what i want to do? i want to post data to server and get response with this format:
public class UserLoginInformation {
private String username;
private String userUniqueId;
}
My interface:
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body Object data);
}
post data:
private void joinUserToApplication(String data) {
AlachiqRestFullProvider signalProvider = new AlachiqRestFullProvider();
SignalRetrofitServiceProviders signalRetrofitServiceProviders = signalProvider.getServices();
Call<List<UserLoginInformation>> call = signalRetrofitServiceProviders.joinUserToApplication(data);
call.enqueue(new Callback<List<UserLoginInformation>>() {
#Override
public void onResponse(Call<List<UserLoginInformation>> call, Response<List<UserLoginInformation>> response) {
List<UserLoginInformation> result = response.body();
final String r = new Gson().toJson(result);
}
#Override
public void onFailure(Call<List<UserLoginInformation>> call, Throwable t) {
t.printStackTrace();
Log.e("onFailure ", t.getMessage());
}
});
}
RestFull provider:
public class AlachiqRestFullProvider {
private SignalRetrofitServiceProviders signalRetrofitServiceProviders;
public AlachiqRestFullProvider() {
OkHttpClient httpClient = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ClientSettings.ALACHIQ_WEB_BASE_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
signalRetrofitServiceProviders = retrofit.create(SignalRetrofitServiceProviders.class);
}
public SignalRetrofitServiceProviders getServices() {
return signalRetrofitServiceProviders;
}
}
data for post:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobileNumber", mobileNumber);
jsonObject.put("userUniqueId", uuid);
jsonObject.put("userPhoneNumbers", phoneContacts);
startService(
new Intent(context, AlachiqRestFullWebServiceProvider.class)
.putExtra("request_type", "joinUserToApplication")
.putExtra("data", jsonObject.toString()));
} catch (JSONException e) {
e.printStackTrace();
}
server response data like with this format:
{"username":"mahdi","userUniqueId":"fwcrwcrwr23234c24"}
server side application to get data is:
Route.post('joinUserToApplication', function *(request, response) {
console.log(request._raw);
response.send({username: "mahdi", userUniqueId: "fwcrwcrwr23234c24"});
});
The POST body that is being serialized is a generic Object.
Create a POJO with the fields that you require and use a deserializer that retrofit understands
public interface SignalRetrofitServiceProviders {
#POST("joinUserToApplication")
Call<List<UserLoginInformation>> joinUserToApplication(#Body UserLoginInformation data);
}
Please note the parameter of the function is not changed to UserLoginInformation
http://square.github.io/retrofit/#restadapter-configuration

How to get list of things in Retrofit

There's something about Retrofit that I'm not getting. I'm following examples on the web, but can't get it to even compile. I am able to access the data from the RESTful service via old school (i.e. HttpGet/HttpResoponse) so I know the service works. It returns a bunch of EmployeeData (as oppose to just one EmployeeData)
In the app gradle file:
dependencies {
...
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
...
}
The url for the RESTful service endpoint is:
https://com.somewhere/PhoneDirectoryService/api/Employees/
I have defined a string for the base url:
<string name="https_phone_directory_service_baseurl">https://com.somewherePhoneDirectoryService/api/</string>
Interface
public interface EmployeesService {
#GET("Employees.json") // the string in the GET is end part of the endpoint url
public Call<List<EmployeeEndpointResponse>> listEmployees();
}
Response
public class EmployeeEndpointResponse {
private List<EmployeeData> employees; // EmployeeData is a POJO
// public constructor is necessary for collections
public EmployeeEndpointResponse() {
employees = new ArrayList<EmployeeData>();
}
public static EmployeeEndpointResponse parseJSON(String response) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Type collectionType = new TypeToken<List<EmployeeData>>(){}.getType();
Gson gson = gsonBuilder.create();
EmployeeEndpointResponse employeeEndpointResponse = gson.fromJson(response, EmployeeEndpointResponse.class);
return employeeEndpointResponse;
}
}
Get the data
public static boolean getEmployeeData(Context context) {
Resources resources = context.getResources();
URI uri = null;
try {
uri = new URI(resources.getString(R.string.https_phone_directory_service_baseurl));
}
catch (URISyntaxException exception) {
Log.e("getEmployeeData", exception.toString());
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(uri.toString())
.addConverterFactory(GsonConverterFactory.create())
.build();
Call<List<EmployeeEndpointResponse>> call = service.listEmployees();
EmployeesService service = retrofit.create(EmployeesService.class);
// this does not compile
// error: <anonymous com.somewhere.utilities.Utilities$1> is not
// abstract and does not override abstract method
// onFailure(Call<List<EmployeeEndpointResponse>>,Throwable) in Callback
call.enqueue(new Callback<List<EmployeeEndpointResponse>>() {
#Override
public void onResponse(Response<List<EmployeeEndpointResponse>> response) {
List<EmployeeEndpointResponse> myList = response.body();
// Successfull request, do something with the retrieved messages
}
#Override
public void onFailure(Throwable t) {
// Failed request.
}
});
// so I tried this which gives compile error
// retrofit2.Callback<java.util.List
// <com.somewhere.gson.EmployeeEndpointResponse>>)
// in Call cannot be applied to anonymous retrofit2.Callback
// <com.somewhere.gson.EmployeeEndpointResponse>)
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
// handle response here
EmployeeEndpointResponse employeeEndpointResponse = (EmployeeEndpointResponse)response.body();
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
}
What do I need to do?
Data looks like:
[
{"Name":"Smith, Ken J.",
"Cell":"",
"EmailAddress":"Ken.Smith#somewhere.com",
"Location":"West",
"Phone":"555-555-5555",
"Address":"PO Box 555 5555 Del Norte",
"City":"Jackson",
"State":"WY",
"Zip":"85555",
"Latitude":42.24976,
"Longitude":-107.82171},
{"Name":"Cox, Daniel B.",
"Cell":"",
"EmailAddress":"daniel.cox#somewhere.com",
"Location":"West",
"Phone":"(555) 555-5516",
etc ...}
]
Add the dependency
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
}
Generate the http client
private static OkHttpClient getOkHttpClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
return okClient;
}
Getting the data
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(YOUR_URL)
.client(getOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
EmployeesService service = retrofit.create(EmployeesService.class);
Call<EmployeeEndpointResponse> call = service.listEmployees();
call.enqueue(new Callback<EmployeeEndpointResponse>() {
#Override
public void onResponse(Call<EmployeeEndpointResponse> call, Response<EmployeeEndpointResponse> response) {
EmployeeEndpointResponse employeeEndpointResponse = response.body();
//manage your response
}
#Override
public void onFailure(Call<EmployeeEndpointResponse> call, Throwable t) {
}
});
Parsing JSON
Your POJO doesn't need any aditional methods to parse JSON. Just generate the code with GSON anotations with http://www.jsonschema2pojo.org/

Categories

Resources