项目中需要用到retrofit,就写了一个简单的demo,通过get请求去showapi提供的猜一猜接口获取谜语和谜底,返回的数据是json格式的,如下
{ "showapi_res_code": 0, "showapi_res_error": "", "showapi_res_body": { "Answer": "肚里有文章", "Title": "吃棉花拉线团", "id": "19663" } }
具体效果如下:
https://route.showapi.com/151-2?id=19663&showapi_appid=6135&showapi_timestamp=20150911150757&showapi_sign=67bce2329b8346fbb8f76bcd9c97b626
1.根据我们要访问的url确定创建API接口,代码如下
package acitvity.jason.com.retrofitdemo.rest.service; import acitvity.jason.com.retrofitdemo.rest.model.ApiResponse; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Query; /** * Created by jason.Yin on 9/10/15. * E-mail:[email protected] */ public interface RiddlessService { //https://route.showapi.com/151-2?id=&showapi_appid=6135&showapi_timestamp=20150910150022&showapi_sign=55f25393057839b57110f6730eb4ca6a //url中只有showapi_timestamp需要变化的 @GET("/151-2?id=&showapi_appid=6137&showapi_sign=5a648105eb0841c88454ffc32377e760") void getRiddles(@Query("showapi_timestamp") String timeStamp, Callback<ApiResponse> callback); }
package acitvity.jason.com.retrofitdemo.model; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; /** * Created by jason.Yin on 9/10/15. * E-mail:[email protected] * <p/> * "showapi_res_body": { * "Answer": "露了馅", * "Title": "饺子脱皮", * "id": "22242" * } */ @Parcel public class ResponseBody { @SerializedName("Title") private String riddlesContent; @SerializedName("Answer") private String riddlesAnswer; public String getRiddlesContent() { return riddlesContent; } public String getRiddlesAnswer() { return riddlesAnswer; } @Override public String toString() { return "ResponseBody{" + "riddlesContent='" + riddlesContent + '\'' + ", riddlesAnswer='" + riddlesAnswer + '\'' + '}'; } }
package acitvity.jason.com.retrofitdemo.rest.model; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; import acitvity.jason.com.retrofitdemo.model.ResponseBody; /** * Created by jason.Yin on 9/10/15. * E-mail:[email protected] */ @Parcel public class ApiResponse { @SerializedName("showapi_res_body") private ResponseBody responseBody; public ResponseBody getResponseBody() { return responseBody; } }
package acitvity.jason.com.retrofitdemo.rest; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; /** * Created by jason.Yin on 9/10/15. * E-mail:[email protected] */ public class ItemTypeAdapterFactory implements TypeAdapterFactory{ @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this,type); final TypeAdapter<JsonElement> elementTypeAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out,value); } @Override public T read(JsonReader in) throws IOException { JsonElement jsonElement = elementTypeAdapter.read(in); if (jsonElement.isJsonObject()){ JsonObject jsonObject = jsonElement.getAsJsonObject(); //showapi_res_code只需要把这个换成你自己需要的字段就行 if (jsonObject.has("showapi_res_code") && jsonObject.get("showapi_res_code").getAsInt() == -1){ throw new IllegalArgumentException(jsonObject.get("message").getAsString()); } } return delegate.fromJsonTree(jsonElement); } }.nullSafe(); } }
4.创建RestAdapter访问网络数据
package acitvity.jason.com.retrofitdemo.rest; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import acitvity.jason.com.retrofitdemo.rest.service.RiddlessService; import retrofit.RestAdapter; import retrofit.converter.GsonConverter; /** * Created by jason.Yin on 9/10/15. * E-mail:[email protected] */ public class RestClient { private static final String BASE_URL = "https://route.showapi.com"; private RiddlessService riddlessService; public RestClient() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new ItemTypeAdapterFactory()) .create(); RestAdapter restAdapter = new RestAdapter.Builder().setLogLevel(RestAdapter.LogLevel.FULL).setEndpoint(BASE_URL).setConverter(new GsonConverter(gson)).build(); riddlessService = restAdapter.create(RiddlessService.class); } public RiddlessService getRiddlessService() { return riddlessService; } }
5.在Activity中使用RestAdapter访问网络数据
package acitvity.jason.com.retrofitdemo; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.Date; import acitvity.jason.com.retrofitdemo.model.ResponseBody; import acitvity.jason.com.retrofitdemo.rest.RestClient; import acitvity.jason.com.retrofitdemo.rest.model.ApiResponse; import butterknife.Bind; import butterknife.ButterKnife; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Bind(R.id.tv_no_network) TextView displayNetworkStatus; @Bind(R.id.tv_riddles_title) TextView riddlesTitle; @Bind(R.id.tv_riddles_answer) TextView riddlewAnswer; @Bind(R.id.bt_show_answer) Button showAnswer; private ResponseBody responseContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); getRiddles(); showAnswer.setOnClickListener(this); } @Override protected void onResume() { super.onResume(); if (isNetworkConnected()) { displayNetworkStatus.setVisibility(View.GONE); } else { displayNetworkStatus.setVisibility(View.VISIBLE); riddlesTitle.setVisibility(View.GONE); riddlewAnswer.setVisibility(View.GONE); } } private boolean isNetworkConnected() { ConnectivityManager mgr = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE); if (mgr != null) { NetworkInfo networkInfo = mgr.getActiveNetworkInfo(); if (networkInfo != null) { return networkInfo.isConnected(); } } return false; } public void getRiddles() { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String date = simpleDateFormat.format(new Date()); Log.d("jason", "date=" + date); new RestClient().getRiddlessService().getRiddles(date, new Callback<ApiResponse>() { @Override public void success(ApiResponse apiResponse, Response response) { responseContent = apiResponse.getResponseBody(); riddlesTitle.setText(responseContent.getRiddlesContent()); showAnswer.setVisibility(View.VISIBLE); } @Override public void failure(RetrofitError error) { Log.d("aa", "error" + error.toString()); riddlesTitle.setVisibility(View.GONE); riddlewAnswer.setVisibility(View.GONE); displayNetworkStatus.setVisibility(View.VISIBLE); displayNetworkStatus.setText(error.toString()); } }); } @Override public void onClick(View view) { if (R.id.bt_show_answer == view.getId()) { if ("显示谜底".equals(showAnswer.getText())) { riddlewAnswer.setVisibility(View.VISIBLE); riddlewAnswer.setText(responseContent.getRiddlesAnswer()); showAnswer.setText("换个谜语"); } else { getRiddles(); showAnswer.setText("显示谜底"); riddlewAnswer.setVisibility(View.GONE); } } } }
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "acitvity.jason.com.retrofitdemo" minSdkVersion 11 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.squareup.retrofit:retrofit:1.6.1' compile 'com.jakewharton:butterknife:7.0.1' compile 'org.parceler:parceler:1.0.3' compile 'com.google.code.gson:gson:2.3.1' }