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
Related
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 am using StringEntity with AndroidAsyncHttp but it is deprecated. Is there another way to get this to work while sending my json string in the way I am to my web service?
public void getPropertyImagesAsync(final String[] params) {
JsonStructure jsonStructure = new JsonStructure();
jsonStructure.methodName = "getPropertyWorkorders";
jsonStructure.serviceName = "mobileapi";
jsonStructure.parameters = params;
String jsonString = new Gson().toJson(jsonStructure);
StringEntity entity = null;
try {
entity = new StringEntity(jsonString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(visnetawrap, BASE_URL + "/amf/gateway/?contentType=application/json", entity, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
AppUtils.outputJsonString(s);
}
#Override
public void onSuccess(int i, Header[] headers, String s) {
AppUtils.outputJsonString(s);
}
});
}
Keep an eye on the situation, but you can probably get away with continuing to use StringEntity for now.
StringEntity is actually part of Apache HTTP, not android-async-http. Google deprecated the entire Apache HTTP API in SDK 22, and removed it from the stub library in SDK 23 (M preview). It reportedly still runs on M devices, but you can't compile it.
Unfortunately, android-async-http was designed around Apache HTTP. Worse, it exposes its use of that API, so it can't be changed without causing breakage. The developers have announced plans to ensure continued support, possibly by introducing a dependency on the standalone Apache HTTP.
I recommend you to use a library for your network operations. You can use Retrofit. It's a powerful library and easy to use.
http://square.github.io/retrofit/
I'm using Android Asynchronous Http Client .
Which one is true: to create one AsyncHttpClient for each request, or to create one client for all requests.
Now I have one Singltone RequestHelper like this:
private RequestHelper() {
mContext = MyApplication.getContext();
baseUrl = mContext.getString(R.string.base_url);
}
public static RequestHelper getInstance() {
if (instance == null) {
instance = new RequestHelper();
}
return instance;
}
public void performLoginRequest(String username, String password, GsonHttpResponseHandler gsonHttpResponseHandler) {
AsyncHttpClient client = new AsyncHttpClient();
attachHeaders(client);
client.post(mContext, baseUrl + "/login", null, "application/json", gsonHttpResponseHandler);
}
public void getCountries(GsonHttpResponseHandler gsonHttpResponseHandler) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(mContext, baseUrl + "/countries", null, gsonHttpResponseHandler);
}
You can see that now I'm creating AsyncHttpClient object for every request
I think creating one Asynctask for each request is better for code review. I think both can be done if you manage each case and give the right input to the AsyncTask to let it know which function it needs to execute, But you might end with a 2000 lines class instead of 10 class of 200 lines with explicit class name, so anytime you would need to change something you might need to check the whole 2000 lines and after changing something you would need to be sure you didn't break anything in the class. But this is just a matter of opinions.
From this example found on your source link, it is okay to create one client for all requests. You can used it multiple.
import com.loopj.android.http.*;
public class TwitterRestClient {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Therefore, the answer is to create one client for all requests.
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.
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) {
}