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)
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 am using volley to parse my api, when i pass the valid credentials it works fine gives me ab auth token and if the credentials are wrong i still want it to parse the response but its giving me "No authentication challenges found" and JSONObject response as null response in return. Is it something with volley or it is something with the php script??
private void sendRequest_getAuth(){
try {
JSONObject jsonBody = new JSONObject();
jsonBody.put("phone", "phn in numeric");
jsonBody.put("password", "pswd");
JsonObjectRequest JSONRequest = new JsonObjectRequest(Request.Method.POST, "the api url", jsonBody,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
jresponse=response;
show_getAuth(jresponse);
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("onError_response",jresponse.toString());
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
show_getAuth(jresponse);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(JSONRequest);
}
required Response which should be parsed:-
{
"errors": [
{
"message": "Invalid Credentials"
}
]
}
Try the following thing:-
Check you Url in Postman (or any applicaiton) and pass invalid credentials and check what response you are receiving from webservice. If you are not getting respose as you have mentioned in you question then its Server side issue (PHP).
Now if you are getting response as above, the kindly check if successfull login and error in login response pattern is same.
Because if the json signature mismatches it won't be able to parse.
If its entering in Error callback kindly mention what is the error server is returning.
Have look at this link too...
java.io.IOException : No authentication challenges found
In case of any doubts, feel free to reply...
https://www.instagram.com/developer/authentication/
Im on the last step (three). Im making a GET request and Im getting a response but it is now successful, im getting code 400 saying im missing client_id but I am not missing it. I saw a few others with the same problem but no clear solution. Below is the relevant code please have a look im a little bit new to retrofit.
//here I am creating the request to send through retrofit...
<!-- language: java -->
TokenRequest request = new TokenRequest();
request.setClient_id(Constants.CLIENT_ID);
request.setClient_secret(Constants.CLIENT_SECRET);
request.setGrant_type(Constants.AUTORISATION_CODE);
request.setRedirect_uri(Constants.REDIRECT_URI);
request.setCode(code);
//this is the actual request
final Call<TokenResponse> accessToken = ServiceManager.createTokenService().getAccessToken(request);
accessToken.enqueue(new Callback<TokenResponse>() {
#Override
public void onResponse(Call<TokenResponse> call, Response<TokenResponse> response) {
mtext.setText("hello");
if(response.isSuccess()){
mtext.setText("success");
}else{
try {
mtext.setText(response.errorBody().string());
//Log.d("mylog", response.errorBody().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the moment its not going into the if block but showing the error in the else block.
I had my API interface built incorrectly, you can check the comments for the incorrect one. The correct one is the one below:
#FormUrlEncoded #POST("/oauth/access_token")
Call<TokenResponse> getAccessToken(#Field("client_id") String client_id,
#Field("client_secret") String client_secret,
#Field("redirect_uri") String redirect_uri,
#Field("grant_type") String grant_type, #Field("code") String code);
This was really tricky for me being new to retrofit hope it helps if you're stuck at the same problem!
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.