Best ERROR RESPONSE I should send from Server to Android? - android

I am developing a communication's system between an Android App and a Server.
I am using Retrofit API for the Android's communication with the Server.
When I do a GET (from Android side) to get info from the Server, I use a CallBackTask method like this:
public void testGet()
{
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(UserApi.SERVER)
.build();
final UserApi svc = restAdapter.create(UserApi.class);
if (svc != null) {
CallableTask.invoke(new Callable<Test>() {
#Override
public Test call() throws Exception {
Test g = svc.getTest();
System.out.println("getVdd() = "+g.getVdd()+"+ getResp() = "+g.getResp());
return g;
}
}, new TaskCallback<Test>() {
#Override
public void success(Test result) {
Intent i = new Intent(getApplicationContext(),SplashRapidoActivity.class);
startActivity(i);
}
#Override
public void error(Exception e) {
Toast.makeText(
getApplicationContext(),
"Unable to connect, please try again.",
Toast.LENGTH_SHORT).show();
}
});
}
}
Where the Test.class is a POJO class with variables and his getters and setters:
public class Test {
String vdd;
String resp;
public Test()
{
}
public void setVdd(String vdd) {
this.vdd = vdd;
}
public String getVdd() {
return vdd;
}
public void setResp(String resp)
{}
public String getResp()
{
return resp;
}
}
So, my question is, which is the best ERROR RESPONSE i could send from the server if there aren't valid values for the Test.class in the server?

Actually there is no "the best error response". It depends on your requirements. But there is widely used architecture called REST and Retrofit was designed in according with REST interaction. REST basically is just a set of rules which clients and servers understand without any documentation.
So if you want to retrieve(GET) some object/data from server by REST you can either receive it with status 200 or receive status 404 with appropriate description of error(or without it) inside body.
Here some more to read.

The best error response is one that make sense to you as a developer. I wouldn't mess with the default HTTP status/error codes. Instead I would send a specific response from the server. For example, keep the HTTP response code at 200 but in the data you send to the app set it to "ERROR: no values." or whatever you prefer. Then, in your Android app, check the response to see if it contains values or an error. Something like
if(resp.startsWith("ERROR:")){
// Do error handling //
} else {
// Normal code //
}

Related

Retrofit : Only one HTTP method is allowed. Found: GET and GET

I use Retrofit to get data from RestApi to my application in Android.
I have a problem with Get method with parameter.
When I run my code I get RetrofitError: [...]: Only one HTTP method is allowed. Found: GET and GET.
myWebService:
#GET("/tag/{id}")
void getById(#Path("id") int id, Callback<Data> pResponse);
MainActivity:
String url = "xyz";
retrofit = new RestAdapter.Builder()
.setEndpoint(url)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
myWebService = retrofit.create(MyWebService.class);
myWebService.getById(id, new Callback<Data>() {
#Override
public void success(Data data, Response response) {
Log.d(CLASS_TAG, data.toString());
}
#Override
public void failure(RetrofitError error) {
}
});
For example: when i changed #GET("/tag/{id}") to #GET("/tag/1") everything works well.
Check you backend for Authorization filter :
you might have authorized the route /tag/but you also should authorize /tag/* to match the path with parameters syntax.
Please tell us about you backend so we can give you more inputs if needed.

Http GET request not happened after OnError in retrofit

I am new to Retrofit and using com.squareup.retrofit:retrofit:1.9.0. I am having form filling in android application which can enter address and when clicking on save button
it will make http GET request using flatmap operator in retrofit, and it will give a error responses if user enter the wrong pin code saying that "invalid pin code"
Once after I receive the error response, It will go OnError() callback and I am allowing the user to edit the pin code again and clicking on save button again , my retrofit API is not making a http request. How to resolve this issue?
ApiClient.createAddress(contact).subscribe(mObserver );
mObserver = new Subscriber<Contact>() {
#Override public void onCompleted() {}
#Override public void onError(Throwable e) {
onNetworkError(e);
}
#Override public void onNext(Contact contact) {
saveContact(contact);
}
};
public static Observable<Contact> createAddress(Contact mAddress)
{
final String name = mAddress.getName();
final String company = mAddress.getCompany();
final String country = mAddress.getCountry();
final Observable<Contact> createAddressObservable =
sService.createAddress(name,company,country)
.flatMap(new Func1<AddressResponse, Observable<? extends Contact>>() {
#Override
public Observable<? extends Contact> call(
AddressResponse addressCreateResponse) {
if (addressCreateResponse.isSuccess()) {
return Observable.just(addressCreateResponse.getAddress());
}
else {
final String errorMessage = addressCreateResponse.getMessage();
return null;
}
});
return createAddressObservable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
In the above code when I enter wrong pin code it goes to the call back onError , then I allow user to edit the pincode and click on save button , it will call ApiClient.createAddress(contact, null).subscribe(mObserver)
which is not making http get request again. Please help on this.

Why is Retrofit responding with 404 error code?

I have written a Retrofit code which has a Yii2 backend. The problem is: when I call the web-service on backend, it works perfectly. However, when I try to call the web-service from android device; it throws a response code of 404. Here is what I have done:
I am targeting a url which looks like: http://192.168.0.104/root-web/web/index.php?r= and it had an end-point: root/register
public interface RegisterAPIService {
#POST("practice/register")
Call<RegisterModel> registerUser(#Body RegisterDetails registerDetails);
}
The code in my activity looks like this..
RegisterDetails registerDetails = new RegisterDetails(email, mobile, password);
RegisterAPIService registerAPIService = retrofit.create(RegisterAPIService.class);
Call<RegisterModel> call =registerAPIService.registerUser(registerDetails);
call.enqueue(new Callback<RegisterModel>() {
#Override
public void onResponse(Response<RegisterModel> response) {
Log.d("Message", "code..."+response.code() + " message..." + response.message()+" body..."+response.body());
}
#Override
public void onFailure(Throwable t) {
}
});
} else {
// Error
}
}
I am getting 404 for the above code. I am trying to send my parameters in the form of a POST request. Please guide me through it.
You should call your development machine from the device, by its ip address, based on how they are connected. Also you can use Android Reverse Tethering tools for your operating system. for further study and options you can take a look at the answers to this question

Retrofit returns null error message with status 400

I have created an app to use REST api developed by me. Android client is written with retrofit library.
there I have created an interface as ObjectIFaceAsync
public interface ObjectIFaceAsync {
#POST("/")
public void addArea(
#Body Area area,
Callback<JsonElement> data
);
}
then I implemented it in a button click
Area pojoArea = new Area();
pojoArea.setArea(area.getText().toString());
pojoArea.setDistrict(district.getText().toString());
pojoArea.setProvince(province.getText().toString());
pojoArea.setAreaType(areaType.getSelectedItem().toString());
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(URLs.ENDPOINT + "/restaddarea")
.build();
ObjectIFaceAsync objectIFaceAsync = restAdapter.create(ObjectIFaceAsync.class);
try {
objectIFaceAsync.addArea(
pojoArea, new Callback<JsonElement>() {
#Override
public void success(JsonElement jsonElement,retrofit.client.Response response) {
if (jsonElement.getAsJsonObject()
.get("status").getAsString().equals("s")) {
//show a message
} else {
//show another message
}
}
#Override
public void failure(RetrofitError retrofitError) {
//show a failure message
}
}
);
} catch (Exception e) {
}
I have used the same endpoint to and sent a get request that is not having a JSON #Body. It works fine. Here I always get an error. means it always runs the failure method. I got displayed the
retrofitError.getMessage();
and
retrofitError.getResponse().getStatuse();
They show null and 400 respectively.
Can someone tell what I have to do to get this corrected. or what I have done wrong here.
thanks.
Use
retrofitError.getBody()
to get String or
retrofitError.getBodyAs(MyError.class)
if you want to map the error json to object

Push Messages using REST api in android

I am developing an Android app using Parse.com website. In which whatever user sends data that must be received by receiver, but here I have to use REST api. I succeeded to send data to Parse website but now I have to Push that data with the help of REST api only. I am confused with REST api. Help to solve it.
You can use a library for that. I would suggest this one https://github.com/kodart/Httpzoid
It has clean API and type-safe data.
Here is a simple usage example
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.execute();
Or more complex with callbacks
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.handler(new ResponseHandler<Void>() {
#Override
public void success(Void ignore, HttpResponse response) {
}
#Override
public void error(String message, HttpResponse response) {
}
#Override
public void failure(NetworkError error) {
}
#Override
public void complete() {
}
}).execute();
It is fresh new, but looks very promising.

Categories

Resources