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.
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);
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 am trying to upload an image to a PHP file on a server using the POST method. I have been trying to do this using LoopJ AndroidAsyncHttp with no success. The server also requires a basic auth username and password. So far, I have been able to successfully POST the regular data parameters (These are simple string key-valued pairs like: "name":"joe") and get a response from the server. However, as soon as I try to attach the image to the POST request, the request fails giving me the following errors:
Error Message: null
Error Cause: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
The code that I am using follows the examples given at http://loopj.com/android-async-http/ very closely. Here is the code that I am using:
RequestParams params = new RequestParams();
params.put("name",name);
String path = "/path/to/img";
File myFile = new File(path, "picture.png");
if( myFile.exists() ) {
try {
params.put("picture", myFile);
} catch(FileNotFoundException e) {
Log.d("App","Error Attaching Picture: " + e.toString());
}
} else {
Log.d("App","File DOES NOT exist");
}
String urlString = "url-to-server";
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("User", "Pass");
client.post(urlString, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
super.onSuccess(statusCode, headers, responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
super.onFailure(statusCode, headers, responseBody, error);
Log.d("App","Upload Failed!");
Log.d("App","Error Message: " + error.getMessage());
Log.d("App", "Error Cause: " + error.getCause());
}
#Override
public void onStart() {
super.onStart();
}
});
So what am I doing wrong here?
I have also double checked and the file that I am reading to get the image does exist and it does have data in it, so I have ruled that out as a potential cause.
I have been struggling with this issue a little too long now.
Thanks in advance to anyone who can help!
This was a bug in the old 1.4.4 version of AsyncHTTPClient. It can be fixed by updating to the 1.4.8 version. In your build.gradle file under the dependencies section it should look like this:
compile 'com.loopj.android:android-async-http:1.4.8'
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.
Here is the code that I have used for Async Http requests using loopj.
AsyncHttpClient loopjClient = new AsyncHttpClient();
PersistentCookieStore loopjCookieStore = new PersistentCookieStore(this);
loopjClient.setCookieStore(loopjCookieStore);
RequestParams loopjParams = new RequestParams();
loopjParams.put("username", username);
loopjParams.put("email", emailID);
loopjParams.put("password", password);
Log.d(TAG, "RRRRRRlll");
loopjClient.post("http://www.example.com/", loopjParams, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int k,String response) {
super.onSuccess(k, response);
Log.d(TAG, "RRRRRR "+ response );
}
});
And my server response string is just the following with out the HTML tags
{"AUTHENTICATION":{"SUCCESS":false,"USERNAME":"unregistered","USERID":0},"ALERTBOX":{"SHOW":true,"MESSAGE":"Message : Username or email ID already registered. Please choose a different one."}}
But loopj doesnt print the above string in onSuccess().
Can you tell how to get the string or do I have to fall back to default Android http library ?
Thanks in advance.
EDIT
Instead of 'example'(my site) if I replace it with 'facebook' I just get the following string as response with a 200 response code <?xml version="1.0" encoding="utf-8"?>
Since the result of AUTHENTICATION failed, I'm wondering if the status code that your server return is not 200. You can override onFailure method to deal with this situation.
#Override
public void onFailure(Throwable e) {
Log.d(TAG, e.toString());
}
Edit
Another guess, have you added the following line in your Manifest.xml?
<uses-permission android:name="android.permission.INTERNET" />
Edit Again
I saw your edit, and it seems that you have an buggy LogCat as #shailendra-rajawat mentioned in comment, since LogCat printed only the first line. Try Toast instead:
#Override
public void onSuccess(int k, String response) {
Toast.makeText(getBaseContext(), response, 1).show();
}
I found this post for configuring your LogCat, and maybe you can give it a try. (Mine is 5000 FYI)