how to fix 500 response code error in Retrofit Android Studio - android

I am facing problem implementing the POST RETROFIT in openrouteservices maps to get round route.
Attached photo below is the error log.Enter image description here
This is my API Interface
Call<Round> getRoundCoordinates(
/*#Header("Content-Type: application/json") String authHeader ,*/
#Header("Authorization") String authHeader,
#Query("coordinates") List<List<Double>> coordinates,
#Query("length") int length,
#Query("seed") int seed
);
and 500 Error code is showing. Anyone who can help .Thanks in Advance :)

Error 500 is a server internal error. So either it cannot handle your parameter values or it is totally independent from client-side, the error lays in server code.

From the official document -
The 500 (Internal Server Error) status code indicates that the server
encountered an unexpected condition that prevented it from fulfilling
the request.
So you need to discuss with you backend team about it because it is an error occurred in the server, not your app (Client-side)

Related

Axios POST request gives a "Network Error" when adding image to FormData structure in React Native

I'm currently building a simple app in React Native 0.62.2 for Android. I've been having some trouble with axios 0.19.2 (or even the fetch API) when trying to upload images to my API (which is written in node.js/express). The POST request is formulated as follows:
// UserService.js
export const postNewUser = async (newUser) => {
try {
const photo = {
uri: newUser.avatar.uri,
type: 'image/jpg',
name: newUser.avatar.fileName,
};
const formData = new FormData();
Object.keys(newUser).forEach(key => formData.append(key, newUser[key]));
formData.append('avatar', photo);
const response = await api.post('/users', formData);
return response.data;
} catch (err) {
console.log('TRACE error posting user: ', err);
return;
}
}
Here, the property newUser.avatar.uri is set by means of an image picker library, namely #react-native-image-picker 1.6.1. It gives me a NetworkError whenever I append the photo variable into the FormData. Setting the URI manually with some random image from the web results in the same error. Debbuging it from the Browser, it prints out some sort of stack trace like this one:
TRACE error posting user: Error: Network Error
at createError (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\axios\lib\core\createError.js:16)
at EventTarget.handleError (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\axios\lib\adapters\xhr.js:83)
at EventTarget.dispatchEvent (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\event-target-shim\dist\event-target-shim.js:818)
at EventTarget.setReadyState (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:575)
at EventTarget.__didCompleteResponse (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:389)
at C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\Network\XMLHttpRequest.js:502
at RCTDeviceEventEmitter.emit (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189)
at MessageQueue.__callFunction (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:425)
at C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:112
at MessageQueue.__guard (C:\Users\Dell\Documents\Projetos\SmartestVet\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:373)
If I, for example, comment out the line formData.append('avatar', photo); it works perfectly, i.e., my API receives the request accordingly. So I think this might not be a CORS-related issue. Also, other requests, such as GETs and even other POSTs are working just fine.
I know there's a bunch of other related posts here in SO and also in GitHub, some of them related to the exact same issue. But none of the solutions I found worked out for me.
In case someone wants to check out how the routes in my API are implemented just hit me up and I will provide the code here.
Thanks in advance for any help you might give me!
I'm having the same issue, using the formData but without the file upload it works just fine. I did a lot of research and what I've found is an old issue that still's active in the react native repo. The solution that's suggested is using a library called rn-fetch-blob but I couln't implement it on my project. If you can make it work share your work around please.

Android Retrofit + Rxjava: How to get response on non200 code?

This is how my request looks like:
ApiService apiService = retrofit.create(ApiService.class);
Observable<Response<UserUpdateResponse>> response = apiService.updateUser(Utils.getHeader(), object);
response.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onSuccessUpdate,
this::onErr,
this::hideDialogLoading);
It's supposed to return 'code':'205' 'msg':'successfully update'. But when server response any code 201,202 (anything not 200) it will go to error.
Here is the Error.
java.net.ProtocolException: HTTP 205 had non-zero Content-Length: 121
So how do I prevent it from error, or how do I get error body? Thank you!.
HTTP response codes have a predefined definition and some have requirements that they must fullfill to be considered a valid HTTP payload. You cannot redefine what these codes mean for your application and expect well-implemented clients to accept it.
Looking specifically at HTTP 205 - Reset Content, which has the following requirement:
Since the 205 status code implies that no additional content will be provided, a server MUST NOT generate a payload in a 205 response.
Generally applications will just return HTTP 200 for all requests and include application-specific error codes in the payload. What you're doing does not make much sense.
So technically, I can get response 2xx. The problem was that server response body in response code 205 that suppose to be null (https://www.rfc-editor.org/rfc/rfc7231#section-6.3.6). So after set body null on server, android side works fine.

Events subscription via webhooks using MS graph Android SDK

I am implementing events subscription using MS graph android SDK. Below is the code.
IGraphServiceClient mGraphServiceClient = GraphServiceClientManager.getInstance(context).getGraphServiceClient();
mGraphServiceClient.getSubscriptions().buildRequest().post(getSubscription(email, expirationDate), subscriptionICallback);
private Subscription getSubscription(String email, Calendar expirationDate) {
Subscription subscription = new Subscription();
subscription.expirationDateTime = expirationDate;
subscription.notificationUrl = "<Webhook link>";
subscription.changeType = "created,updated";
subscription.resource = "me/events";
subscription.clientState = Base64.encodeToString(email.getBytes(), Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
return subscription;
}
The request body generated through this always throws the error:
Error during http request Error code: InvalidRequest
Error message: Could not process subscription creation payload. Are all property names spelled and camelCased properly?
POST https://graph.microsoft.com/v1.0/subscriptions
SdkVersion : graph-android-v1.0.0
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...]
{"#odata.context":"https://graph.microsoft.com/v1.[...]
400 : Bad Request
E/DefaultHttpProvider[sendRequestInternal] - 286: [...]
E/DefaultHttpProvider[sendRequestInternal] - 286: [Some information was truncated for brevity, enable debug logging for more details]
E/DefaultHttpProvider[sendRequestInternal] - 286: Throwable detail:
com.microsoft.graph.http.GraphServiceException: Error code: InvalidRequest
Error message: Could not process subscription creation payload. Are all property names spelled and camelCased properly?
POST https://graph.microsoft.com/v1.0/subscriptions
SdkVersion : graph-android-v1.0.0
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...]
{"#odata.context":"https://graph.microsoft.com/v1.[...]
400 : Bad Request
[...]
[Some information was truncated for brevity, enable debug logging for more details]
at com.microsoft.graph.http.DefaultHttpProvider.handleErrorResponse(DefaultHttpProvider.java:310)
at com.microsoft.graph.http.DefaultHttpProvider.sendRequestInternal(DefaultHttpProvider.java:246)
at com.microsoft.graph.http.DefaultHttpProvider.access$000(DefaultHttpProvider.java:47)
at com.microsoft.graph.http.DefaultHttpProvider$1.run(DefaultHttpProvider.java:129)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
E/agenday.com.pgi.agenday.ui.BaseActivity: create Subscription exceptionError code: InvalidRequest
Error message: Could not process subscription creation payload. Are all property names spelled and camelCased properly?
POST https://graph.microsoft.com/v1.0/subscriptions
SdkVersion : graph-android-v1.0.0
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI[...]
{"#odata.context":"https://graph.microsoft.com/v1.[...]
400 : Bad Request
[...]
[Some information was truncated for brevity, enable debug logging for more details]
but the same request body is working fine in graph explorer,
I have tried many things now but unable to resolve it. How can I get this to work for subscriptions in Android, I can't find any resources for this online.
The issue was due to the BaseSubscription model in Microsoft graph SDK where it is setting "#odata.type":"microsoft.graph.subscription" by default and subscription api is not supporting this in request body and throwing the error: 400
So I resolved it by explicitly making "#odata.type" to null in the subscription model and pass it to post request which worked successfully for me.
Thanks!

Robospice caching when exception occured

I wan't to achieve next.
Depends on json content deside put or not to put data to Robospice Cache.
Sometimes data returned from the server is not valid. For example our authorization token goes off time. So we shouldn't cache this response.
But i can't find API which can help me to solve this trouble.
Here is how i am using requests now:
getSpiceManager().execute(getRequestCreator().getAllCategories(), getRequestCreator().getLastCacheKey(),
DurationInMillis.ONE_MINUTE * 120, new JSONCategoryListener(mCategories));
So the actual response is normal (status 200), but json content is telling me about exception.
So, what you want to get? It is right behavior for server. Server returns 200, means that request is successful. But it not guarantee, that wasn't some internal error of 'business logic' on server, such as not valid data or anything else.
EDITED
May be you can use your custom error handler:
class MyErrorHandler implements ErrorHandler {
#Override public Throwable handleError(RetrofitError cause) {
//check response on errors
}
}
And in createRestAdapterBuilder():
new RestAdapter.Builder()..setErrorHandler(new MyErrorHandler());
EDITED 2
You can implement in your robospice service method putDataInCache(Object cacheKey, T data), and in your listener check errors in content, and if no error then add it to cache, or remove it from cache

Previous Android Response Being Added to Status Line

I'm using Volley to communicate with an API.
I am sending a request and on success of that request I immediately fire off another one, using the same message queue.
The issue I have is the second request is responding with the following error:
java.net.ProtocolException: Unexpected status line: {"id":47}HTTP/1.1 200 OK
The {"id":47} is the response body from the first request. I'm not even going near the status line in my code and the requests are fairly simple.
What on earth is happening?! Is it a bug within Volley?
I would suppose that the status line "HTTP/1.1 200 OK" is expected to be before the actual response content {"id":47} - according to the error message it seems to be exactly reversed.
In my case, the server return content when status code is 204,
api should not return data when 204 responses

Categories

Resources