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/
Related
I'm new to Android, I'm using AsyncHttpClient to call a POST API. But the API is not even being called
Below is my code:
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Key","random-key");
JSONObject body = new JSONObject();
body.put("clientId","random-client-id");
body.put("question",question);
HttpEntity entity = new StringEntity(body.toString());
client.post( getApplicationContext(),"http://localhost:3000/api/Chats/GetAnswer", entity,"application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
List<List<Answer>> answers = new ArrayList<>();
try {
JSONArray answersJson = response.getJSONArray("answers");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
Toast toast = Toast.makeText(getApplicationContext(),"Unable to get answers for the question sent",Toast.LENGTH_SHORT);
toast.show();
}
});
`
Any hints of what I'm doing wrong??
Solved, it appear that the problem was in AndroidManifest.xml Since I'm using the internet and calling an external API, I had to add:
<uses-permission android:name="android.permission.INTERNET"/>
And another thing. When working locally and testing using the emulator, we should write
http://10.0.2.2:port-number/ instead of http://localhost:port-number/. Because android emulator runs in a virtual machine. Therefore, localhost will be emulator's own loopback address.
Please put debugger at your method and Make sure its calling or not , I think you have passed wrong context value And as my point of View its better to User Retrofit than AsyncHttpClient.
Use Retrofit if you are communicating with a Web service.
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
i am fetching 104 variables from MySQL through php in android and trying to show in list view but its taking almost 1 - 2 minutes to load values how to speed up the data fetching.
i am using json for fetching data, any other library's for fast fetching.
please explain with complete example.
Try the Android Asynchronous Http Client library
Features
Using upstream HttpClient of version 4.3.6 instead of Android provided DefaultHttpClient
Compatible with Android API 23 and higher
Make asynchronous HTTP requests, handle responses in anonymous callbacks
HTTP requests happen outside the UI thread
Requests use a threadpool to cap concurrent resource usage
GET/POST params builder (RequestParams)
Multipart file uploads with no additional third party libraries
Streamed JSON uploads with no additional libraries
Handling circular and relative redirects
Tiny size overhead to your application, only 90kb for everything
Automatic smart request retries optimized for spotty mobile connections
Automatic gzip response decoding support for super-fast requests
Binary protocol communication with BinaryHttpResponseHandler
Built-in response parsing into JSON with JsonHttpResponseHandler
Saving response directly into file with FileAsyncHttpResponseHandler
Persistent cookie store, saves cookies into your app’s SharedPreferences
Integration with Jackson JSON, Gson or other JSON (de)serializing libraries with BaseJsonHttpResponseHandler
Support for SAX parser with SaxAsyncHttpResponseHandler
Support for languages and content encodings, not just UTF-8
For more details please visit these link :
http://loopj.com/android-async-http/
Here's an example of using it :
pdialog.setMessage("Veuillez patienter!");
pdialog.show();
RequestParams params = new RequestParams();
params.put("user_login", username);
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://yourUrl.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
loading = true;
AdapterPrincipal adapterPrincipal;
String s = "";
try {
s = new String(responseBody, "UTF-8");
Log.d("Error", s.toString());
JSONObject arrg = new JSONObject(s);
JSONArray query = arrg.getJSONArray("query");
Log.i("result from query ", "" + query);
for (int i = 0; i < query.length(); i++) {
try {
pdialog.dismiss();
JSONObject object = query.getJSONObject(i);
String dateinsertannonce = object.getString("date_insert_annonce");
Log.i("date", dateinsertannonce);
String datevente = object.getString("vendu");
String marque = object.getString("marque");
String Clomn_Model = object.getString("model");
String Clomn_Prix = object.getString("prix");
String Clomn_Kilometrage = object.getString("kilometrage");
String Clomn_BoiteVitesse = object.getString("boite_vitesse");
String Clomn_Energie = object.getString("energie");
String Clomn_Source = object.getString("source");
String Clomn_Url = object.getString("url");
String Clomn_PHOTO = object.getString("images_noms");
String Maj = object.getString("derniere_maj");
int id = object.getInt("id");
voitureList = databaseHelper.getAllVoiture(username, currentLength);
listView.setAdapter(new AdapterLogin(getActivity(), voitureList, username, currentLength));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
});
}
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.