I'm using loopj to talk to a rest server which has different HTTP response codes for specific successful responses (i.e 200, 202). The AsyncHttpResponseHandler has an onSuccess(String content) callback but nothing that returns the HTTP response code. How can I get this?
Try
#Override
public void onSuccess(int statusCode, String content) {
}
Related
I am trying to get make a post request in Android using AsyncHttpClient using this code:
JSONObject jsonParams=new JSONObject();
try {
jsonParams.put("email", email);
}
catch (Exception e){
}
try {
StringEntity entity = new StringEntity(jsonParams.toString());
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(),URL,entity, "application/json", new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {}
});
I am trying to access this data sent in the post request in my Python server. However, whenever I do request.json in my Python server, I get 'None' as response.
I also tried request.get_json(force=True) but getting 404 error code.
I dont really know if the data is being sent by the client APP or I am making a mistake while trying to retrieve it at the server side. Please help me with this issue.
String content = new String(responseBody);
Log.e("SUCCESS_RESP",""+content);
Hi I've been using this free GIT library for some time now and I just experience a very very weird problem
I have a URL (web API) that returns a JSON formatted data.
Yes, it exist on browser I tried all main browser out there and it is showing.
The problem is when I used it on my AsyncHttp LoopJ it returns a 404 error, which fires
onFailure(int statusCode, Header[] headers, byte[] responseBytes, Throwable throwable)
status code is 404 and throwable message is "not found".
I've test other URL on my other project and it works only not this specific URL. That guarantees that it works on other URL.
I cant say that the API has a problem, since it shows JSON data on web browser.
I clean the project rebuild nothing works.
Please anyone had the same struggle here.
I check the manifest, check internet connection all good. Like I said it works on other URL, except this one.
PS. I like the simplicity of this library thats why I dont want to switch to other similar libraries out there.
What im using is this class
public class TerminalClient {
private static AsyncHttpClient client = new AsyncHttpClient();
public static AsyncHttpClient syncHttpClient = new SyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
getClient().setTimeout(1000 * 10);
getClient().get((url), params, responseHandler);
}
public static void asyncPost(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
getClient().setTimeout(1000 * 10);
getClient().post((url), params, responseHandler);
}
public static void post(String url, RequestParams params, BaseJsonHttpResponseHandler baseJsonHttpResponseHandler) {
getClient().setTimeout(1000 * 10);
getClient().post((url), params, baseJsonHttpResponseHandler);
}
private static AsyncHttpClient getClient() {
if (Looper.myLooper() == null)
return syncHttpClient;
return client;
}
}
I just switch to Post to Get. That did it, pretty weird. Yep.
This can be a reference for future guys who will bump in this kind of problem.
-Cheers
Hello guys I'm new to restful service.
My friend created REST backend with Spring.
When I post this URL --> http://smartcar.tobaconsulting.com:9999/api/v1/login with postman or angularjs http.post, it's fine.
You guys can check it out in postman by including this body
{ "username":"alvin", "password":"alvin" }
and set content type to JSON (application/json).
But when I code to Android, why it's not working and return 500 error code.
My friend said that I'm not including header. I'm using loopj http library http://loopj.com/. Here is my android code
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://smartcar.tobaconsulting.com:9999/api/v1/login", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d(TAG, String.format("status code: %d", statusCode));
}
});
Please help me guys. I trying to solve this problem for hours and haven't find any clue.
Thanks
i checked your URL no error in server response
Access-Control-Allow-Credentials →true
Access-Control-Allow-Methods →GET, POST, PUT, DELETE
Access-Control-Allow-Origin →chrome-extension://mkhojklkhkdaghjjfdnphfphiaiohkef
Access-Control-Expose-Headers →X-AUTH-TOKEN
Content-Length →0
Date →Thu, 07 Apr 2016 08:35:26 GMT
Server →Apache-Coyote/1.1
X-AUTH-TOKEN
→eyJ1c2VybmFtZSI6ImFsdmluIiwiZW1haWwiOiJhbHZpbkBhbHZpbi5jb20iLCJleHBpcmVzIjoxNDYwODgyMTI2MDc4LCJvd25lcmlkIjo2LCJteVJvbGVzIjpbIlVTRVIiLCJBRE1JTiJdfQ==.M9/71trIPbnXxCh7avSWBK42UDXUxWYXZrNOlHhO7iQ=
I would personally suggest using Volley lib for android, there is some useful method inside volley and google strongly recommended that
Transmitting Network Data Using Volley
I'm an experienced developer with android and currently i am developing android application that has Django as its server side on heroku cloud.
I'm pretty new to django and django rest framework so i dont really get how to use it except for the guide on their website.
What i was trying to do recently was using Volley/AsyncHttpClient/Apache Http to contact with my django server.
With each of these libraries i got Http 500 error on django in his console output.
What i tried to do on each of them is adding data to the body or parameters.
On Volley - i overrided the getParams and added them to hash
on AsyncHttpClient - i made RequestParams
on HttpClient(apache) - i used a list of NameValuePair and added them as entity of UrlEncodedForm to the http post request.
i also tried on volley and asynchttpclient to add data to the body of the request and it didn't worked also.
I even thought of changing my server side because of all the trouble Django is causing me , so please if anyone have the answer please give it :)
This is my Server Side(Django):
class User(APIView):
queryset = AppUser.objects.all()
def get(self,request,format=None):
users = AppUser.objects.all()
serialized_users = UserSerializer(users, many=True)
return HttpResponse(serialized_users.data)
def post(self,request):
user_serializer = UserSerializer(data=request.DATA)
if user_serializer.is_valid():
user_serializer.save()
return HttpResponse(status.HTTP_201_CREATED)
return HttpResponse(status=status.HTTP_406_NOT_ACCEPTABLE)
**There's no point to show the urls/models/serializer because it all works on the google chrome with the GET method.
Android(apache http client):
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
paramsList.add(new BasicNameValuePair("user",userJson));
post.setEntity(new UrlEncodedFormEntity(paramsList));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
}
Android (AsyncHttpClient):
try {
RequestParams params = new RequestParams();
params.put("user",userJson);
mClient.post(msg.getText().toString(),params,new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
if(statusCode == 201) Toast.makeText(MainActivity.this,"Success" , Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
} catch (Exception e) {
}
I'm really clueless what to do next because i think i covered all my options contacting my server...
Thanks
If I am not wrong, the message in console just says Http 500 Server error without the cause right?
To debug it more, add following to your settings(base.py)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'ERROR',
'class': 'logging.StreamHandler',
'stream': sys.stderr
},
},
'loggers': {
'django.request': {
'handlers': ['console'],
'propogate': True,
'level': 'ERROR',
}
}
}
This few lines in your settings will print the cause of 500 error in the console, you might get clue to what you are doing wrong.
I'm using this library to request from my web services. It didn't response at all in onSuccess and onFailure sometimes (these are the only two methods I overrides). I tested under 1.4.4 and 1.4.5 (android-async-http-1.4.5-20131110.125018-1, this one is better, but still encounter the problem sometimes). I'm sure it's not the network problem, because my ios app never encounter this problem from the same web services. And I can get response when I refresh immediately after this problem occurs.
Here is my code:
In requester.java
public class Requester
{
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
AsyncHttpClient client = newClient();
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
AsyncHttpClient client = newClient();
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return Settings.BASE_URL + relativeUrl;
}
private static AsyncHttpClient newClient()
{
AsyncHttpClient client = new AsyncHttpClient();
client.setMaxRetriesAndTimeout(Settings.HTTP_TIMEOUT,Settings.HTTP_RETRIES);
return client;
}
}
In my activity who's making http request:
Requester.get(urlRequest, null, new JsonHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONArray objects)
{
Logger.logDebug(TAG, "request success for " + " " + objects.length() + " objects");
}
#Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, java.lang.Throwable throwable, org.json.JSONArray errorResponse)
{
Logger.logError(TAG,"Failed to request");
}
});
I'm using the similar source in a few projects. But all have the same problem. I don't know it's the problem of my code or the android-async-http library. Can anybody help? Thanks.
By the way, I'm normally making 3 requests at the same time by using the same method as the above mentioned source code but with different url.
I confirmed that the problem is related to the multiple requests. My solution is to replace with another library: Volley library. Problem solved!
I encounter this problem as well and upon further investigation I realized that if the json response received is not in proper json format or if the response from the server contains any extra characters you will not get a callback method being called, although the post or get would have been processed the callbacks will not be triggered. Check your response from the server to make sure.