剛開始探索……
第一步先了解要請求的json數據
如我要請求的是:圖靈機器人最簡單的json數據:請求示例爲:
請求示例:
{
“key”:“APIKEY”,
“info”:“你好”
}
返回的數據:
{
“code”:100000,
“text”:”你也好 嘻嘻”
}
那麼就根據這個來創建一個簡單的NewsBean實體類:
public class NewsBean implements Serializable {
private int code;
private String text;
private String url;
public NewsBean() {
}
public NewsBean(String text) {
this.text = text;
}
public NewsBean(int code, String text) {
this.code = code;
this.text = text;
}
public NewsBean(int code, String text, String url) {
this.code = code;
this.text = text;
this.url = url;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
這裏有一點需要特別注意的是:保證我們定製的javabean對象的字段要和服務器返回的數據字段一一對應,不然解析會出錯(PS ^_^複雜的數組類型有待探索,更新….. —————————————————————————————
基本使用:
1、get請求:
要請求的URL 和 KEY 爲:
public class TulingParams {
public static final String TULING_URL = "http://www.tuling123.com/openapi/";
public static final String TULING_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //自己去圖靈註冊一個 免費
}
由上面的數據分析可知 要請求的參數爲”key” 和 “info”,定義服務接口對象:
public interface RetrofitApi {
@GET("api")
Call<NewsBean> getTuringInfo(@Query("key") String key, @Query("info") String info);
}
@GET標識爲get請求,@GET中所填寫的value值和TULING_URL組成完整的路徑,TULING_URL在構造retrofit對象時給出;@Query 標識爲接口查詢的關鍵字,有兩個參數標記爲兩;
當我們的參數過多的時候我們可以通過@QueryMap註解和map對象參數來指定每個表單項的Key,value的值。
在MainActivity中定義一個requestApiByRetrofit方法:
private void requestApiByRetrofit(String info) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(TuringParms.TULING_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitApi api = retrofit.create(RetrofitApi.class);
Call<NewsBean> call = api.getTuringInfo(TuringParms.TULING_KEY, info);
call.enqueue(new Callback<NewsBean>() {
@Override
public void onResponse(Call<NewsBean> call, Response<NewsBean> response) {//打印返回結果
NewsBean news = null;
news = response.body();//將返回的數據解析成一個NewsBean對象
showText.setText(news.getCode()+" -和- "+news.getText());
}
@Override
public void onFailure(Call<NewsBean> call, Throwable t) {
//進行異常情況處理
}
});
}
Retrofit的構建使用的是構造者模式,指定一個baseUrl,添加一個對象轉換器,用於將服務器返回的數據轉換成對應實體類對象。
構造完成以後,調用create方法就可以拿到我們的接口實例。然後再調用我們之前定義好的獲取城市的方法,得到一個call對象,通過call.enqueue即可完成異步的網絡請求。
最後在數據請求成功的時候,通過response.body()即可拿到我們定義在Call< T >中需要返回的對象,數據請求失敗的時候,進行異常的處理。
TextView打印的結果爲:
————————————————待更新———————————————————-