Java tutorial
/* * Copyright 2014 Leonardo Rossetto * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.leonardoxh.temporeal.app.service; import android.app.IntentService; import com.github.leonardoxh.temporeal.app.model.Model; import com.github.leonardoxh.temporeal.app.utils.JsonUtils; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; /** * Esta e nossa classe pai dos servicos */ public abstract class AbstractService extends IntentService { /** * Este e o client que vai executar as nossas requisicoes */ protected final OkHttpClient mClient = new OkHttpClient(); public AbstractService(String name) { super(name); } /** * Este metodo vai fazer as requisicoes HTTP para nos * enviando o modelo se necessario * @param endPoint a URL da requisicao * @param model o modelo para enviar note que se este modelo for null iremos fazer um GET * por que temos um padrao no servidor :) * @param <T> o tipo do modelo (qualquer um que derive de Model) * @return a resposta da URL ou null em caso de falha */ protected <T extends Model> Response makeRequest(String endPoint, T model) { try { Request.Builder requestBuilder = new Request.Builder(); requestBuilder.url(endPoint); if (model == null) { requestBuilder.get(); } else { requestBuilder.post(RequestBody.create(Constants.JSON_MEDIA_TYPE, JsonUtils.toJson(model))); } return mClient.newCall(requestBuilder.build()).execute(); } catch (IOException e) { /* Essa exception sera lancada caso uma falha na * comunicacao aconteca, entao iremos retornar null */ e.printStackTrace(); } return null; } }