http://blog.csdn.net/jiguangcanhen/article/details/39006197
同步的方式:
1)首先定義要接口。注解Get表示使用的Get請求方式,{user}代表要被替換的資料
2)初始化RestAdapter,并利用動态代理來建立的接口對象。
3)使用網絡通路并傳回
異步的方式:
注:body注解,在進行請求前對象會被轉換器進行相應的資料轉換。
前兩部和之前的相同,不同在于最後一個參數變成了CallBack對象。
controller.getLogin(mail, password, new Callback<UserDataModel>() {
@Override
public void failure(RetrofitError error) {
// TODO Auto-generated method stub
}
public void success(UserDataModel ldm, Response response) {
});
可以看到當請求網絡傳回之後,會在failure中和success中進行回調,而且預設的資料轉換器會把相應的json字元串轉換為對象。(當然,我們也可以定義自己的資料轉換器)
定義自己的資料轉換器:
public class MyConverter implements Converter {
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
StringBuffer result = new StringBuffer();
try {
InputStream is = body.in();
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1){
result.append(new String(buffer,"UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public TypedOutput toBody(Objectobject) {
return null;
}
上面的自定義資料轉換器,會在請求成功之後,傳回給我們字元串,而不是相應的被gson轉換過格式的字元串。
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(“url”)
.setConverter(new MyConverter())
.build();
在建立RestAdapter之後建立設定使用自己的資料轉換器就可以了。
我們還可以靈活的進行其他的配置:
1)設定請求攔截器,會在請求發出前,進行攔截。
2)設定錯誤控制器
3)設定log日志。
上面隻是簡單介紹了它的使用,其實它還有很多的功能,Get,Post,Put,Delete,Head……具體請參見官方網址。
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
本文轉自wanqi部落格園部落格,原文連結:http://www.cnblogs.com/wanqieddy/p/4933606.html如需轉載請自行聯系原作者