Retrofit的使用教程(一)

這篇教程基於retrofit1.9版本和android平臺.
以下部分代碼和教程參考自http://square.github.io/retrofit/
準備:
retrofit的下載地址:https://github.com/square/retrofit
如果採用引入jar包的方式的話,也額外引入retrofit的依賴jar包.
因爲retrofit1.9版本不再支持android原生的URLConnection和HttpClient框架.所以必須要引入okHttp2.0框架進行網絡訪問.
下面2個是必要的jar包
okhttp-2.2.0.jar
okio-1.0.2.jar(okhttp的依賴jar包)
下面的jar是功能增強的jar包.根據要使用的功能再去引入.
gson-2.3.jar
appengine-api-1.0-sdk-1.9.12.jar
rxjava-1.0.0.jar
以上jar包可以在github或者maven中央倉庫下載到.注意jar包的版本.
GET方式
1
2
3
4
interface SimpleGET{
  @GET("/"//表明是GET方式. "/"會拼接在setEndpoint(url)中url(主機地址)的後面.
  Response getResponse(); //可以簡單的理解爲網絡訪問完把Response轉換爲一個對象.這裏沒有轉換,還是Response.
} 
訪問,注意在Android上要在異步線程執行下面語句.
1
2
3
4
5
6
7
8
9
10
String url="http://tieba.baidu.com";
RestAdapter adapter=new RestAdapter.Builder().setEndpoint(url).build(); //setEndpoint(url)設置網絡訪問地址的主機地址
SimpleGET create = adapter.create(SimpleGET.class); //retrofit會生成上面的SimpleGET接口的一個的實例.
Response response = create.getResponse();
int status = response.getStatus(); //返回碼
try {
  InputStream in = response.getBody().in(); //response的輸入流.看到網絡訪問的輸入流都很熟悉吧.想轉換成字符串還是json還是圖片就看服務器給的是什麼了.
catch (IOException e) {
  e.printStackTrace();
}

  

POST方式
1
2
3
4
interface SimplePOST{
  @POST("/android"//表明是使用Post方式進行訪問. 並且會把後面的路徑拼接到主機名的後面-->拼接到setEndpoint(url)中的url的後面.
  Response getResponse();
} 
異步線程中執行下面語句.
1
2
3
4
5
6
7
8
9
10
String url="http://tieba.baidu.com";
RestAdapter adapter=new RestAdapter.Builder().setEndpoint(url).build(); //和上面post後面的路徑拼接,想當於訪問http://tieba.baidu.com/android
SimplePOST create = adapter.create(SimplePOST.class);
Response response = create.getResponse();
int status = response.getStatus();
try {
  InputStream in = response.getBody().in();
catch (IOException e) {
  e.printStackTrace();
} 
PATH
path是可以動態替換的.
1
2
3
interface GitHub {
  @GET("/repos/{owner}/{repo}/contributors")
  List<Contributor> contributors(@Path("owner") String owner, @Path("repo") String repo);
網絡訪問部分
1
2
3
4
private static final String API_URL = "https://api.github.com";
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).build();
GitHub github = restAdapter.create(GitHub.class);
List<Contributor> contributors = github.contributors("square""retrofit"); //相當於對路徑中{}部分進行動態替換. 相當於訪問https://api.github.com/repos/square/retrofit/contributors 

  

GsonConverter默認的轉換器
看了上面這一些,可以回想retrofit也沒方便多少啊.下面看一個例子就可以知道retrofit的魅力所在了.
注意需要引入gson的jar包
1
2
3
4
5
6
7
8
9
static class Contributor { //一個pojo類(Plain Ordinary Java Object)簡單的Java對象-->相比javaBean更簡單.
  String login;
  int contributions;
}
  
interface GitHub {
  @GET("/repos/{owner}/{repo}/contributors")
  List<Contributor> contributors(@Path("owner") String owner, @Path("repo") String repo);
} 
網絡訪問部分.
1
2
3
4
5
6
7
RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).build(); //默認設置了GsonConverter的轉換器.把response直接解析爲一個POJO對象.
GitHub github = restAdapter.create(GitHub.class);
//訪問這個地址返回的是一個JsonArray,JsonArray的每一個元素都有login和contributions這2個key和其對應的value.提取出來封裝進POJO對象中.
List<Contributor> contributors = github.contributors("square""retrofit"); 
for (Contributor contributor : contributors) {
    Log.v("retrofit", contributor.login + " (" + contributor.contributions + ")");
}
打印的結果:
JakeWharton (487)
pforhan (48)
edenman (40)
..........
直接方法https://api.github.com/repos/square/retrofit/contributors得到的數如下的json串.
[
{      
"login": "JakeWharton",
"id": 66577,
............
"site_admin": false,
"contributions": 487
},
{
"login": "pforhan",
.............
"site_admin": false,
"contributions": 48
},
{
"login": "edenman",
"................
"site_admin": false,
"contributions": 40
},
...........
]
可以看到retrofit的魅力所在了
 
 
自定義的Converter(StringConverter)
Response可以獲得輸入流,我們可以把它轉換成任何想要的格式.
自定義的StringConverter轉換器
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
class StringConverter implements Converter{
  
  @Override
  public Object fromBody(TypedInput input, Type type) throws ConversionException { //response輸入流到對象的轉換,
  try {
    InputStream in = input.in(); //獲取了輸入流,就可以根據意願隨意轉換了.
    String str = convertStream2String(in);
    return str;
  } catch (IOException e) {
    e.printStackTrace();
  }
  
  return null;
  }
  
private String convertStream2String(InputStream in) throws IOException { //inputStream轉換爲String
  BufferedReader reader=new BufferedReader(new InputStreamReader(in));
  StringBuilder sb=new StringBuilder();
  String line=null;
  while((line=reader.readLine())!=null){
    sb.append(line);
    sb.append("\n");
  }
  return sb.toString();
}
@Override
public TypedOutput toBody(Object obj) { //對象到輸出流的轉換
  return null;
 }
  
}
1
2
3
4
interface StringClient {
  @GET("/")
  String getString(); //方法的返回值是String,需要StringConverter轉換器Converter把Response轉換爲String.
} 
異步線程調用
1
2
3
4
5
String url="http://tieba.baidu.com";
RestAdapter adapter=new RestAdapter.Builder().setEndpoint(url).setConverter(new StringConverter()).build();
StringClient create = adapter.create(StringClient.class);
String str = create.getString();

  第二片地址http://www.cnblogs.com/laiqurufeng/p/4484889.html

第三片地址http://www.cnblogs.com/laiqurufeng/p/4484916.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章