Static Http Client not giving callbacks - android

I used Loopj Android library for Post requests it works fine when I don't use Static Http Client but when I use Static Http Client it does not give any callback here is my code for class of HttpClient
import com.loopj.android.http.*;
public class MyHttpClient {
private static final String BASE_URL = "http://www.google.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
System.out.println("post called");
}
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Here is how I call it
MyHttpClient.post("", params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
and I have added Internet permission in manifest so there is no issue of permissions here
kindly help

Related

Android http post with composed objects

I'm trying to invoke a REST web service from Android with . For this purpose i created a class like this:
public class HttpUtils {
public static final String BASE_URL1 = AppConstants.hostname;
private static AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
public HttpUtils() throws NoSuchAlgorithmException {
}
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);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return relativeUrl;
}
Then i created a service layer in order to call the method post. The customer gave me the structure of JSON to send:
{
"wsMode":"nuovo",
"wsTokenLogin":"&1I1BY!M$$YEMFKI0YX&",
"crmcttCognome": "Xavi",
"crmcttNome": "Alonso",
"crmcttIndirizzo": "via Alcide de Gasperi",
"crmcttCivico": "1",
"crmcttLocalita": "Napoli",
"crmcttCdLocalita": "",
"crmcttProv": "NA",
"crmcttCap": "80100",
"crmcttTel1": "08123232332",
"crmcttTel2": "",
"crmcttMobile1": "",
"crmcttMobile2": "",
"crmcttEmail1": "",
"crmcttEmail2": "",
"crmcttNota": "ok",
"crmcttIdstcontatto": "N",
"crmcttIdpromoter": "61",
"crmcttDtRilevaz": "20180806",
"crmcttOraRilevaz": "1530",
"crmcttLuogoRilevaz": "",
"prodotti": [{
"crmcprIdprodotto": "01",
"crmprdCdprodotto": "MATE",
"crmprdDsprodotto": "MATERASSI"
}]}
The request i have created has the following structure:
RequestParams rp = new RequestParams();
rp.put("wsMode", "nuovo");
rp.put("wsTokenLogin", token);
rp.put("crmcttCognome", lead.getCognome());
rp.put("crmcttNome", lead.getNome());
rp.put("crmcttIndirizzo", lead.getIndirizzo());
rp.put("crmcttCivico", lead.getCivico());
rp.put("crmcttLocalita", lead.getLocalita());
rp.put("crmcttCdLocalita", lead.getCdLocalita());
rp.put("crmcttProv", lead.getProvincia());
rp.put("crmcttCap", lead.getCap());
rp.put("crmcttTel1", lead.getTelefono1());
rp.put("crmcttTel2", lead.getTelefono2());
rp.put("crmcttMobile1", lead.getMobile1());
rp.put("crmcttMobile2", lead.getMobile2());
rp.put("crmcttEmail1", lead.getEmail1());
rp.put("crmcttEmail2", lead.getEmail2());
rp.put("crmcttNota", lead.getNota());
rp.put("crmcttIdstcontatto", lead.getIdContatto());
rp.put("crmcttIdpromoter", lead.getIdPromoter());
rp.put("crmcttDtRilevaz", lead.getDataRilevazione());
rp.put("crmcttOraRilevaz", "");
rp.put("prodotti",prodottiCliente);
rp.setUseJsonStreamer(true);
where prodottiCliente is array of objects that i have transformed into String with:
String jsonProdottiAddClient = gson.toJson(prodottiAddClient);
After the call, all elements are stored into db except "prodotti". In debug i can see that the list is not empty.
If i try to execute the post call by Postman, all information are stored including prodotti informations. Can you give me some advice to solve the problem?

How to call asp.net Web API from android device

I have a web api controller:
// POST: api/CountriesAPI
[ResponseType(typeof(Country))]
public async Task<IHttpActionResult> PostCountry(Country country)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Countries.Add(country);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = country.CountryID }, country);
}
I don't know how how to consume this from android. please help.
I've used the Android HTTP Client available here and found it very simple and easy to use.
You can then do a POST with code something like below:
public class HTTPClient
{
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler)
{
client.get(url, params, responseHandler);
}
public static void get(String url, FileAsyncHttpResponseHandler responseHandler)
{
client.get(url, responseHandler);
}
public static void post(Context context, String url, StringEntity entity, String contentType, AsyncHttpResponseHandler responseHandler)
{
client.post(context, url, entity, contentType, responseHandler);
}
}
HTTPClient.post(this, <server_url>, entity, "application/json", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response)
{
// Do Something
}
#Override
public void onFailure(Throwable error, String content)
{
// Do Something else
}
});
You can try Libraries like Volley (Requires you to write boilerplate code) or RetroFit
You can make get and post requests using them, do read about Pojos and model creation before you start. And also how do Callbacks work.

Returning to calling function when a http request has finished

I'm trying to do implement login using a ASP.Net Web Api into an Android application.
What I have so far are functions that work, just that I want to make the login request kind of synchronous instead of asynchronous.
I'm using Android Asynchronous Http Client like they say on their website.
public class ApiInterface {
public static final String ApiURL = "http://******/api/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get4Login(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return ApiURL + relativeUrl;
}
}
And I have this function in LoginActivity:
private boolean doLogIn(String user, String pass) {
boolean result = false;
if (user.trim().isEmpty() || pass.trim().isEmpty()) {
return false;
}
RequestParams params = new RequestParams();
params.add("user", user);
params.add("pass", pass);
ApiInterface.get4Login("Auth", params, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable error) {
Toast.makeText(MyApp.getContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
//***Here I want to set the doLogIn() function result depending on the response from the server;***
Toast.makeText(MyApp.getContext(), "Lista sesizari incarcata!", Toast.LENGTH_LONG).show();
}
});
return result;
}
Is there any way to do this?
On your MyTextHttpResponseHandler class should define a variable named result and set type is boolean,default to false,then define a method to get the result value,like
public boolean getResult(){return this.result;}
then you can change the result value on onSuccess and onFailure method.
Next your doLogIn method will like this
private boolean doLogIn(String user, String pass) {
//boolean result = false;
if (user.trim().isEmpty() || pass.trim().isEmpty()) {
return false;
}
RequestParams params = new RequestParams();
params.add("user", user);
params.add("pass", pass);
MyTextHttpResponseHandler myTextHttpResponseHandler = new MyTextHttpResponseHandler(this);
ApiInterface.get4Login("Auth", params, myTextHttpResponseHandler);
return myTextHttpResponseHandler.getResult();
}

How do I call REST API from an android app? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm new to android and new to programming as well. How do I call a REST api (GET/POST request) from an android app. Please suggest me a good tutorial, or give me an idea to start with.
If you want to integrate Retrofit (all steps defined here):
Goto my blog : retrofit with kotlin
Please use android-async-http library.
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/
http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes
Create a class :
public class HttpUtils {
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);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa#123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

Loopj AndroidAsyncHttp setTimeout

I'm using loopj 1.4.4 library to make HTTP request on my android device with 4.2.2.
setTimeout method is not working as expected:
public class RestClient {
private static final int CONNECTION_TIMEOUT = 1000;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
client.setTimeout(CONNECTION_TIMEOUT);
client.setMaxRetriesAndTimeout(1, CONNECTION_TIMEOUT);
client.get(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return Config.API_URL + relativeUrl;
}
}
Using the code above I receive a timeout (specifically a onFailure callback) after
more or less 40 seconds...where am I wrong?
I think my code is not very different from this one: Loopj's AsyncHttpclient not setting the correct timeout

Categories

Resources