LoopJ AndroidAsyncHttp is returning response in OnFailure - android

i am new to AndroidAsyncHttp.
i created a class httptester :
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 relativeUrl;
}
and in my activity did the following:
RequestParams params = new RequestParams();
params.put("FTID", HTTPRequestUserAuthentication.AppID);
params.put("UUID", MainActivity.uuid);
params.put("TYPE", "11");
params.put("DateTimeStamp", DateTimeStamp);
params.put("SDFVersionNb", SDFVersionNb);
httptester.post(MainActivitySharedPref.GetValue(MyApplication.getContext(), "WebService_URL")+MyApplication.getContext().getResources().getString(R.string.url_get_user_data), params,new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
super.onSuccess(statusCode, headers, responseString);
Log.e(TAG, "sucess: " + responseString);
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "failure: " + responseString);
Log.e(TAG, "failurecode: " + statusCode);
super.onFailure(statusCode, headers, responseString, throwable);
}
});
after calling the client, the correct response is being returned but it is being returned in OnFailure and not in OnSuccess. i also printed the status code in onfailure and it is 200 which supposedly should be OK.
any help would be appreciated.

So you call in your request
new JsonHttpResponseHandler()
But you need
new AsyncHttpResponseHandler()

Related

Post request returns empty response body Android?

I'm using android-async-http for rest request. When I doing post request then the response body is empty. When I use postman for the same request I received a response as JSONObject.
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(getResources().getString(R.string.api_user), getResources().getString(R.string.api_password));
String requestAddress = getResources().getString(R.string.api_base_address) + getResources().getString(R.string.api_event_address);
JSONObject params = new JSONObject();
params.put("name", mEditTextName.getText().toString());
params.put("place", mEditTextPlace.getText().toString());
params.put("dateAndTime", DateUtils.sdfWithFullTime.format(DateUtils.sdfWithTime.parse(mEditTextDate.getText().toString())));
Log.d(TAG, "onClick: " + params.toString());
StringEntity stringParams = new StringEntity(params.toString());
client.post(getApplicationContext(), requestAddress, stringParams, "application/json", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.e(TAG, "onFailure: error during creating event " + responseString,throwable );
Toast.makeText(getBaseContext(),"Error during creating event",Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(getBaseContext(),"Successfully create event",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getBaseContext(), EventListActivity.class);
startActivity(intent);
}
});
} catch (Exception e) {
Log.e(TAG, "createEvent: error during creating event", e);
}
}
Check parameters and base url, use volley or retrofit library to Post request.

how to send post request in android

how to send post request in android
I use async http clint library
I use this methode for get and I need this for post
client.get(getString(R.string.server2) + "culture_types", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
}
});
private static AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("param1", "Test"); // Put parameter name
client.post(Url, params, new TextHttpResponseHandler(){
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
}
});

Android GET Http request from API

Hello I'm trying to receive some data from this API
http://docs.sygictravelapi.com/1.1/
The problem is that I'm getting on failure all the time with these exceptions:
Failure cz.msebera.android.httpclient.client.HttpResponseException:
Unauthorized Status Code: 401
I think the problem is that I don't send a Header!
My code is:
RequestParams params = new RequestParams();
params.put("location", locationParameter);
params.put("x-api-key", API_KEY);
AsyncHttpClient client = new AsyncHttpClient();
client.get(API_URL, params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int status, Header[] headers, JSONObject response)
{
Log.d("App", "JSON: " + response.toString());
}
#Override
public void onFailure(int status, Header[] headers, Throwable ex, JSONObject response)
{
Log.e("Dimos", "Failure " + ex.toString());
Log.d("Dimos", "Status Code: " + status);
Toast.makeText(MainActivityController.this, "Failure", Toast.LENGTH_SHORT).show();
}
});

How to send post request with x-www-form-urlencoded body with loopj-async-http library

i m trying to post data in body with x-www-form-urlencoded but i failed
private void sendData(final String toekn) {
RequestParams params = new RequestParams();
params.put("_token", toekn);
StringEntity entity=null;
try {
entity = new StringEntity(params.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropClient.post(getBaseContext(), "", entity, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.e("see", response.toString());
Toast.makeText(SplashActivity.this, response.toString()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
// Do something with the response
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable e) {
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
}
above is code i have tried but always get failure .. api works perfect in postman i have attached pic for understanding params ..
image1
image2
static class
public class PropClient {
private static final String BASE_URL = "";
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(Context context, String url, StringEntity entity, AsyncHttpResponseHandler responseHandler) {
// client.addHeader("Accept", "application/json");
client.addHeader("Content-Type", "application/x-www-form-urlencoded");
entity.setContentType("application/json");
client.setUserAgent("android");
client.post(context, getAbsoluteUrl(url), entity, "application/json", responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
String url = BASE_URL + relativeUrl;
return url;
}
}
if u want to use volley u can check my answer
compile 'com.android.volley:volley:1.0.0'
private void getVolley(final String token, String url) {
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(SplashActivity.this, response + " success", Toast.LENGTH_SHORT).show();
Log.e("volley", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SplashActivity.this, error.toString() + "", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "android");
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("_token", token);
return params;
}
};
jsonObjRequest.setRetryPolicy(new DefaultRetryPolicy(30 * 1000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(jsonObjRequest);
}
You need to add header like below :-
public static void setHttpClient(AsyncHttpClient c, Application application) {
c.addHeader("Accept-Language", Locale.getDefault().toString());
c.addHeader("Host", HOST);
c.addHeader("Connection", "Keep-Alive");
//noinspection deprecation
c.getHttpClient().getParams()
.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
// Set AppToken
c.addHeader("AppToken", Verifier.getPrivateToken(application));
//c.addHeader("AppToken", "123456");
// setUserAgent
c.setUserAgent(ApiClientHelper.getUserAgent(AppContext.getInstance()));
CLIENT = c;
initSSL(CLIENT);
initSSL(API.mClient);
}
You need to see this link for more info.

send data in raw using asynhttpclient

I m posting JSON in raw with this Url [URL I post data to][1]
param is=eventName="countryList"
codes
private void testApp() {
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("key", "value");
StringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(), "url", entity, "application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("good",response.toString());
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("fail",throwable.toString());
}
});
} catch (Exception e) {
}
}
error:fail: cz.msebera.android.httpclient.client.HttpResponseException: Internal Server Error
change fromStringEntity entity = new StringEntity(new Gson().toJson(jsonParams));
to:**StringEntity stringEntity = new StringEntity(jsonParams.toString());**
And Also override
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
your response return jsonobject not array

Categories

Resources