import it.bluecore.filoo.model.UserLogin;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import java.io.UnsupportedEncodingException;
import cz.msebera.android.httpclient.entity.StringEntity;
/**
* Created by ricksam on 12/11/2016.
*/
public class ApiHelper {
private AsyncHttpClient cliente;
private String URL = "http://apiserver/";
private Gson gson;
private String CONTENT_TYPE_JSON = "application/json";
private final int DEFAULT_TIMEOUT = 30 * 1000;
public ApiHelper(){
this.cliente = new AsyncHttpClient();
this.cliente.setTimeout(DEFAULT_TIMEOUT);
this.gson = new Gson();
}
public void Auth(UserLogin login, ApiResponse response){
String link=URL + "Api/Auth";
StringEntity entity = null;
String json = gson.toJson(login);
try {
entity = new StringEntity(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cliente.post(App.getContext(), link, entity, CONTENT_TYPE_JSON, response.getResponseHandler(gson));
}
}
/******************************************************************************************/
import android.widget.Toast;
import it.bluecore.filoo.application.App;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import cz.msebera.android.httpclient.Header;
/**
* Created by ricksam on 12/11/2016.
*/
public abstract class ApiResponse<T> {
private Class<T> classOfT=null;
public ApiResponse(Class<T> classOfT){
this.classOfT = classOfT;
}
public abstract void onSuccess(T entityResponse) ;
public AsyncHttpResponseHandler getResponseHandler(final Gson gson){
return new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String result = null;
if (responseBody != null)
result = new String(responseBody);
T objectResult = (T) gson.fromJson(result,classOfT);
ApiResponse.this.onSuccess(objectResult);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(App.getContext(), error.getMessage(), Toast.LENGTH_LONG);
}
};
}
}
/******************************************************************************************/
compile 'com.loopj.android:android-async-http:1.4.9'
compile 'com.google.code.gson:gson:2.3.1'
/******************************************************************************************/
UserLogin login = new UserLogin();
login.setLogin(User);
login.setPassword(Password);
ApiHelper api = new ApiHelper();
api.Auth(login, new ApiResponse<ReturnUser>(ReturnUser.class) {
@Override
public void onSuccess(ReturnUser entityResponse) {
view.showUser(entityResponse.getUser().getFullName());
}
});