1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
/**
*
*/
public class GSONTask<T> extends AsyncTask<HttpUriRequest, Void, T> {
/**
* L'interface d'écoute des resultats.
*/
public static interface OnGSONResult<T>
{
/**
* Sera appelé quand l'objet JSON sera recu.
* @param res
*/
public void onGSONResult(T res);
/**
* Sera appelé quand une erreur a eu lieu pendant la requête.
* @param error
*/
public void onGSONFailure(Throwable error);
}
private Class<T> gsonClass;
private OnGSONResult<T> callback;
private Throwable error;
private static Gson gson = new Gson();
/**
* Définit le callback pour les résultats.
* @param cb L'interface de callback utiliser.
*/
public GSONTask(Class<T> cl, OnGSONResult<T> cb)
{
this.gsonClass = cl;
this.callback= cb;
}
@Override
protected T doInBackground(HttpUriRequest ... params) {
T ret = null;
InputStream entityStream = null;
try {
HttpClient localClient = getHttpClient();
HttpResponse response = null;
for (HttpUriRequest request : params)
response = localClient.execute(request);
if (response == null)
throw new IOException("No response received ! Did you pass any request ?");
int respCode = response.getStatusLine().getStatusCode();
if (respCode >= 400)
throw new IOException(response.getStatusLine().getReasonPhrase());
HttpEntity entity = response.getEntity();
entityStream = entity.getContent();
String charset = (entity.getContentEncoding() == null) ? null : entity.getContentEncoding().getValue();
if (charset == null)
charset = Charset.defaultCharset().name();
Reader reader = new InputStreamReader(entityStream,charset);
Log.i("GSONTask","Decoding response from server...");
ret = (T) gson.fromJson(reader, this.gsonClass);
} catch (Throwable t) {
Log.w("GSONTask","Error while retrieving JSON",t);
this.error = t;
} finally {
if (entityStream != null) {
try { entityStream.close(); } catch (Exception ex) { Log.e("GSONTask","Failed to gracefully close the entity stream !",ex); }
}
}
return ret;
}
/**
* Surchargez cette fonction pour créer le lien vers un autre client, ou pour ajouter des paramètres au client (agent-string / timeouts / ...).
* @return HttpClient
*/
protected HttpClient getHttpClient() {
return new DefaultHttpClient();
}
@Override
protected void onPostExecute(T result) {
if (this.callback != null) {
if (this.error != null)
this.callback.onGSONFailure(this.error);
else
this.callback.onGSONResult(result);
}
}
} |
Partager