網絡通訊框架Retrofit2html
1 概要
Retrofit2的簡介以及特色
Retrofit2使用配置(導包,權限等)
Retrofit2中經常使用的註解介紹
Retrofit2實現http網絡訪問
GET與POST請求
同步請求和異步請求
Retrofit2實現文件上傳
Retrofit2進行大文件下載java
2 Retrofit2的特色及簡介
簡介
Retrofit翻新,改型,改良
Retrofit是針對於Android/Java的、基於okHttp的、一種輕量級並使用註解方式和動態代理的網絡請求框架,是目前比較流行的網絡框架!
Retrofit是square公司開源系列的精品之一,簡單好用,效率高,基於REST的架構風格,本框架的主要開發人Jake Wharton
REST Representational State Transfer簡稱REST,表述性狀態轉移傳遞
一種軟件架構的設計風格,針對網絡應用的設計和開發方式
Retrofit讓開發者面向接口去請求服務,使用註解和代理去發起真正的請求,讓開發者更快速的開發應用,省掉一些複雜的邏輯處理
你不用擔憂android6.0不支持httpclient方式的請求,你也不用引入gson去轉換數據與對象,Retrofit都已經完美實現android
特色
性能好,處理快,使用簡單,目前安卓中使用比較的流行網絡請求跨框架之一.(速度上比volley更快!)
支持NIO;(新的IOapi,能夠替代標準的java IO API)
使用註解方式,大大簡化了咱們的URL拼寫形式,並且註解含義一目瞭然,簡單易懂
支持同步和異步執行,使得請求變得異常簡單,只要調用enqueue/execute便可完成
請求的方法參數註解均可以定製
默認是使用OKHttp處理網絡請求的
默認使用Gson來進行數據解析的
相關資料的網址
retrofit官網:
http://square.github.io/retrofit/
github地址:
https://github.com/square/retrofitgit
3 Retrofit2的使用配置github
3.1 modle下build.gradle配置添加以下依賴後進行同步
dependencies {
compile 'com.squareup.retrofit2:converter-gson:2.0.2'//
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.okhttp3:okhttp:3.8.1'
}
同步後External Libraries中會增長:
retrofit-2.3.0
okhttp-3.8.0
okio-1.13.0
gson-2.6.1
converer-gson-2.0.2
3.2 AndroidManifest.xml添加權限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>web
4 Retrofit2經常使用註解
請求方法類
4.1 @GET
GET網絡請求方式
4.2 @PSOT
POST網絡請求方式ajax
@PUT,@DELETE,@PATCH,@HEAD,@OPTIONS,@HTTP
不經常使用請求方式.
參數類
4.3 @Headers
頭信息參數
4.4 @Path
路徑參數,用於替換url路徑中的變量字符替換,也就是url中的{*}中的*部分
(@Path主要用於Get請求)
例如接口:子鏈接地址中/wages/{wageId}/detail
替換部分:{wageId}中的wageId.編程
4.5 @Query
造成單個查詢參數,將接口url中追加相似於"page=1"的字符串,造成提交給服務器端的參數.
(主要用於Get請求數據,用於拼接在拼接在url路徑後面的查詢參數,一個@Query至關於拼接一個參數,多個參數中間用,隔開)
4.5.1,無參數
例如接口:
http://www.weather.com.cn/data/sk/101010100.html
使用註解:
@GET("data/sk/101010100.html")
Call <Weather> getWeather();
4.5.2,單個參數
例如接口:
http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9
造成提交參數的部分:
callback=jsonp9
使用註解:使用註解:
@GET("jp/avlist/202861101/1/")
Call VideoInfo getVideoData(@Query("callback") String callback);json
4.5.3,多個參數
例如接口:
http://www.kuaidi100.com/query?type=yuantong&postid=500379523313"
造成提交參數的部分:
type=yuantong&postid=500379523313
使用註解:
@GET("query")
Call QueryInfo QueryInfo(@Query("type") String type,@Query("postid") String postid,);api
4.6 @QueryMap
查詢參數集合,將url中追加相似於"page=1&count=20"的字符串,造成提交給服務器端的參數.
(主要的效果等同於多個@Query參數拼接,主要也用於Get請求網絡數據。)
例如接口:
http://www.kuaidi100.com/query?type=yuantong&postid=500379523313"
造成提交參數的部分:
type=yuantong&postid=500379523313
使用註解:
Call QueryInfo QueryInfo(@QueryMap Map<String, String> map) ;
4.7 @Url
使用此註解參數後,@GET後無需在添加任何內容.
方法中的@Url參數能夠是全路徑參數,也能夠是子路徑參數,可是baseurl必需要指定.
4.8 @Field
指定form表單中域中每一個控件name以及相應數值
(@Field的用法相似於@Query,主要不一樣的是@Field主要用於Post請求數據。)
4.9 @FieldMap
表單域集合
(主要用於Post請求數據,@FieldMap的用法相似於@QueryMap)
4.10 @Part
Post提交分塊請求
(表單字段,與 PartMap 配合,適合文件上傳狀況)
4.11PartMap
表單字段,與 Part 配合,適合文件上傳狀況;默認接受 Map<String, RequestBody> 類型,非 RequestBody 會經過 Converter 轉換
4.12 @Body
(指定一個對象做爲 request body)非表單請求體
@POST("users/new")
Call<User> createUser(@Body User user);
標記類:
4.13 @FormUrlEncoded
對錶單域中填寫的內容進行編碼處理,避免亂碼.
(用於post請求.)
例如:
@FormUrlEncoded
@POST(「/user/edit」)
Call updateUnableApeName(@Field(「first_name」) String first,
@Field(「last_name」) String last);
4.14 @MultiPart
Post提交分塊請求,若是上傳文件必須指定MultiPart
(請求體是支持文件上傳的 From 表單)
4.15 @Streaming
響應體的數據用流的形式返回
(未使用該註解,默認會把數據所有載入內存,以後經過流讀取內存中數據,因此返回數據較大時,須要使用該註解)
注意:
Map 用來組合複雜的參數;
Query、QueryMap 與 Field、FieldMap 功能同樣,生成的數據形式同樣;
Query、QueryMap 的數據體如今url上,主要用於GET請求.
Field、FieldMap 的數據是在請求體上,主要用於Post請求.
5 Retrofit2代碼實現步驟(Retrofit2五部曲)
1,定義一個接口(用於存放執行網絡請求的方法)
2,實例化Retrofit
3,經過Retrofit實例建立接口服務對象
4,接口服務對象調用其對應的方法,獲取Call對象
5,Call對象來執行網絡請求(同步或者異步請求)
6 Retrofit2發送GET請求
6.1 GET請求方法中無參數
6.2 GET請求方法指定@Path參數和@Query參數
6.3 GET請求,提交表單數據,方法中定義@QueryMap參數
6.4 GET請求,方法中無參數,可是在@Url中定義完整的Url路徑,這種狀況下BaseUrl會被忽略!
6.5 GET請求,指定返回結果爲ResponseBody.
7 Retrofit2發送POST請求
7.1 Post請求,方法中定義@Fild參數,分別指定各個表單控件的名稱
7.2 Post請求,方法中定義@FildMap參數,@FildMap集合中來指定全部控件名稱
8 同步請求和異步請求
同步:調用call對象的excute(),須要開啓子線程!!!
異步:調用call對象的enqueue(Callback<T> callback)方法,請求結果的回調是在主線程中進行的,這點不一樣於OkHttp.
9 Retrofit2進行文件上傳
9.1 Post請求,方法中定義@Part參數,該參數指定file控件的名稱及上傳後文件的名稱
上傳數據類型:multipart/form-data
步驟:鎖定File,建立RequestBody,建立MultipartBody.Part
9.2 Post請求,方法中定義@Body參數,向服務器中上傳多個文件及其餘表單域數據
9.3 Post請求,方法中定義@Part參數,向服務器中上傳多個文件及其餘表單域數據
9.4 Post請求,方法中定義@PartMap參數,向服務器中上傳多個文件及其餘表單域數據
使用此種方式變量的書寫格式:
file"; filename="123.jpg
(表單控件名稱";filename="保存在服務其端的文件名稱)
web端:
Content-Disposition: form-data; name="file"; filename="1.txt"
10 Retrofit2進行文件下載
10.1小文件下載總體加載到內存.
10.2大文件下載需使用@Streaming註解,實現邊下載邊存入sd卡(存入sd卡過程也應該放在子線程中進行,不然會出現異常)
Java 註解
定義:註解(Annotation),也叫元數據。一種代碼級別的說明。它是JDK1.5及之後版本引入的一個特性,與類、接口、枚舉是在同一個層次。它能夠聲明在包、類、字段、方法、局部變量、方法參數等的前面,用來對這些元素進行說明,註釋。
做用分類:
①編寫文檔:經過代碼裏標識的元數據生成文檔【生成文檔doc文檔】
② 代碼分析:經過代碼裏標識的元數據對代碼進行分析【使用反射】
③編譯檢查:經過代碼裏標識的元數據讓編譯器可以實現基本的編譯檢查【Override】
Annotation(註解)是JDK1.5及之後版本引入的。它能夠用於建立文檔,跟蹤代碼中的依賴性,甚至執行基本編譯時檢查。註解是以‘@註解名’在代碼中存在的,根據註解參數的個數,咱們能夠將註解分爲:標記註解、單值註解、完整註解三類。它們都不會直接影響到程序的語義,只是做爲註解(標識)存在,咱們能夠經過反射機制編程實現對這些元數據(用來描述數據的數據)的訪問。另外,你能夠在編譯時選擇代碼裏的註解是否只存在於源代碼級,或者它也能在class文件、或者運行時中出現(SOURCE/CLASS/RUNTIME)。
元數據的做用
若是要對於元數據的做用進行分類,尚未明確的定義,不過咱們能夠根據它所起的做用,大體可分爲三類:
編寫文檔:經過代碼裏標識的元數據生成文檔。
代碼分析:經過代碼裏標識的元數據對代碼進行分析。
編譯檢查:經過代碼裏標識的元數據讓編譯器能實現基本的編譯檢查
代碼實現:Activity
1 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 2 3 private TextView tv_content; 4 private String TAG = this.getClass().getSimpleName(); 5 private String itemName; 6 private String STR_TAG = TAG + "--->***"; 7 protected OkHttpClient okHttpClient; 8 protected Handler deliveryHandler; 9 10 @Override 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.activity_main); 14 findViewById(R.id.btn_retrofit).setOnClickListener(this); 15 tv_content = (TextView) findViewById(R.id.tv_content); 16 17 okHttpClient = OkHttpClientManager.getInstance(this).getOkHttpClient(); 18 deliveryHandler = OkHttpClientManager.getInstance(MainActivity.this).getDeliveryHandler(); 19 } 20 21 @Override 22 public void onClick(View v) { 23 //彈一個對話框,分類選擇: 24 show(); 25 26 } 27 28 private void show() { 29 //建立builder對象。 30 final AlertDialog.Builder builder = new AlertDialog.Builder(this); 31 //設置標題. 32 builder.setTitle("Retrofit2操做"); 33 //設置列表內容,以及點擊事件. 34 //參數:1,String數組.2,點擊事件. 35 final String[] items = { 36 "0指定無參數GET請求", 37 "1指定@Path和@Query參數GET請求", 38 "2指定@QueryMap參數集合GET請求", 39 "3指定@Url參數GET請求", 40 "4指定GET請求返回ResponseBody", 41 "5同步GET請求", 42 "6指定@Fild參數POST請求", 43 "7指定@FildMap參數POST請求", 44 "8指定@Part參數單文件上傳", 45 "9指定@Body多文件上傳帶參數", 46 "10指定@Part經過多文件上傳帶參數", 47 "11指定@PartMap多文件上傳帶參數", 48 "12指定@Streaming大文件下載", 49 }; 50 builder.setItems(items, new DialogInterface.OnClickListener() { 51 @Override 52 public void onClick(DialogInterface dialogInterface, int i) { 53 itemName = items[i] + STR_TAG; 54 switch (i) { 55 case 0: 56 get0(); 57 break; 58 case 1: 59 get1(); 60 break; 61 case 2: 62 get2(); 63 break; 64 case 3: 65 get3(); 66 break; 67 case 4: 68 get4(); 69 break; 70 case 5: 71 get5(); 72 break; 73 case 6: 74 get6(); 75 break; 76 case 7: 77 get7(); 78 break; 79 case 8: 80 get8(); 81 break; 82 case 9: 83 get9(); 84 break; 85 case 10: 86 get10(); 87 break; 88 case 11: 89 get11(); 90 break; 91 case 12: 92 get12(); 93 break; 94 } 95 } 96 }); 97 builder.create().show(); 98 } 99 100 private void get11() { 101 final File file = new File(Environment.getExternalStorageDirectory(), "1.txt"); 102 final File file1 = new File(Environment.getExternalStorageDirectory(), "2.png"); 103 final RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 104 final RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 105 final RequestBody body2 =RequestBody.create(MultipartBody.FORM, "zxn001"); 106 107 // body =MultipartBody.Part.createFormData("file", file.getName(), body).body(); 108 // body1 =MultipartBody.Part.createFormData("file", file.getName(), body1).body(); 109 // final RequestBody body2 = MultipartBody.Part.createFormData("username", "zxn001").body(); 110 111 112 String baseUrl = "http://192.168.1.102/"; 113 new Retrofit.Builder() 114 .baseUrl(baseUrl) 115 .client(okHttpClient) 116 .build() 117 .create(NetService.class) 118 .uploadFilesByPartMap(new HashMap<String, RequestBody>(){ 119 { 120 put("file\"; filename=\""+file.getName(), body); 121 put("file\"; filename=\""+file1.getName(), body1); 122 put("username",body2); 123 } 124 }) 125 .enqueue(new Callback<ResponseBody>() { 126 @Override 127 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 128 try { 129 showResult("onResponse"+response.body().string()); 130 } catch (IOException e) { 131 e.printStackTrace(); 132 } 133 } 134 135 @Override 136 public void onFailure(Call<ResponseBody> call, Throwable t) { 137 showResult("onFailure"+t.getMessage()); 138 } 139 }); 140 } 141 142 private void get12() { 143 final String baseUrl = "http://1251603248.vod2.myqcloud.com/"; 144 final String downUrl = "http://1251603248.vod2.myqcloud.com/4c9adaa7vodtransgzp1251603248/30e0819d9031868223192061218/v.f40.mp4"; 145 new Thread(new Runnable() { 146 @Override 147 public void run() { 148 try { 149 Response<ResponseBody> response = new Retrofit.Builder() 150 .baseUrl(baseUrl) 151 .client(okHttpClient) 152 .build() 153 .create(NetService.class) 154 .download(downUrl) 155 .execute(); 156 157 if (response.isSuccessful()) { 158 deliveryHandler.post(new Runnable() { 159 @Override 160 public void run() { 161 showResult("服務器鏈接成功!"); 162 } 163 }); 164 boolean ok = writeDisk(response.body()); 165 Log.i(TAG, STR_TAG + "run: 下載:" + ok); 166 if (ok) { 167 deliveryHandler.post(new Runnable() { 168 @Override 169 public void run() { 170 tv_content.setText("下載完成!!"); 171 } 172 }); 173 } 174 } else { 175 deliveryHandler.post(new Runnable() { 176 @Override 177 public void run() { 178 showResult("下載失敗!"); 179 } 180 }); 181 } 182 } catch (IOException e) { 183 e.printStackTrace(); 184 } 185 } 186 }).start(); 187 } 188 189 private boolean writeDisk(ResponseBody body) { 190 try { 191 File file = new File(Environment.getExternalStorageDirectory(), "1.mp4"); 192 InputStream inputStream = null; 193 OutputStream outputStream = null; 194 try { 195 byte[] fileReader = new byte[4096]; 196 long fileSize = body.contentLength(); 197 long loadSize = 0; 198 199 inputStream = body.byteStream(); 200 outputStream = new FileOutputStream(file); 201 int len = -1; 202 while ((len = inputStream.read(fileReader)) != -1) { 203 outputStream.write(fileReader, 0, len); 204 loadSize += len; 205 Log.i(TAG, STR_TAG + "已經下載: " + loadSize + "/總大小: " + fileSize); 206 } 207 outputStream.flush(); 208 return true; 209 } catch (IOException e) { 210 return false; 211 } finally { 212 if (inputStream != null) { 213 inputStream.close(); 214 } 215 if (outputStream != null) { 216 outputStream.close(); 217 } 218 } 219 } catch (IOException e) { 220 return false; 221 } 222 } 223 224 private void get10() { 225 File file = new File(Environment.getExternalStorageDirectory(), "1.txt"); 226 File file1 = new File(Environment.getExternalStorageDirectory(), "2.png"); 227 List<MultipartBody.Part> parts = new ArrayList<>(); 228 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 229 RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 230 MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body); 231 MultipartBody.Part part1 = MultipartBody.Part.createFormData("file", file1.getName(), body1); 232 MultipartBody.Part part2 = MultipartBody.Part.createFormData("username", "zxn001"); 233 parts.add(part); 234 parts.add(part1); 235 parts.add(part2); 236 237 // String baseUrl = "http://192.168.1.102/"; 238 String baseUrl = "http://169.254.38.24/"; 239 new Retrofit.Builder() 240 .baseUrl(baseUrl) 241 .client(okHttpClient) 242 .build() 243 .create(NetService.class) 244 .uploadFilesByPart(parts) 245 .enqueue(new Callback<ResponseBody>() { 246 @Override 247 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 248 try { 249 showResult("onResponse" + response.body().string()); 250 } catch (IOException e) { 251 e.printStackTrace(); 252 } 253 } 254 255 @Override 256 public void onFailure(Call<ResponseBody> call, Throwable t) { 257 showResult("onFailure" + t.getMessage()); 258 } 259 }); 260 } 261 262 private void get9() { 263 File file = new File(Environment.getExternalStorageDirectory(), "a.jpg"); 264 File file1 = new File(Environment.getExternalStorageDirectory(), "d.jpg"); 265 MultipartBody.Builder builder = new MultipartBody.Builder(); 266 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 267 RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 268 MultipartBody multipartBody = builder 269 .addFormDataPart("file", file.getName(), body) 270 .addFormDataPart("file", file1.getName(), body1) 271 .addFormDataPart("username", "zxn123") 272 .setType(MultipartBody.FORM) 273 .build(); 274 275 // String baseUrl = "http://192.168.1.102/"; 276 String baseUrl = "http://169.254.38.24/"; 277 new Retrofit.Builder() 278 .baseUrl(baseUrl) 279 .client(okHttpClient) 280 .build() 281 .create(NetService.class) 282 .uploadFilesByody(multipartBody) 283 .enqueue(new Callback<ResponseBody>() { 284 @Override 285 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 286 try { 287 showResult("onResponse" + response.body().string()); 288 } catch (IOException e) { 289 e.printStackTrace(); 290 } 291 } 292 293 @Override 294 public void onFailure(Call<ResponseBody> call, Throwable t) { 295 showResult("onFailure" + t.getMessage()); 296 } 297 }); 298 299 } 300 301 private void get8() { 302 //指定上傳文件 303 File file = new File(Environment.getExternalStorageDirectory(), "3.jpg"); 304 // RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file); 305 306 //封裝請求體 307 // RequestBody body = RequestBody.create(MediaType.parse("application/otcet-stream"), file); 308 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 309 MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body); 310 311 312 //http://192.168.1.100/MyUploadServer/servlet/UpLoadFileServlet 313 // String baseUrl = "http://192.168.1.102/"; 314 String baseUrl = "http://169.254.38.24/"; 315 316 new Retrofit.Builder() 317 .baseUrl(baseUrl) 318 .client(okHttpClient) 319 .build() 320 .create(NetService.class) 321 .postUpLoadFile(part) 322 .enqueue(new Callback<ResponseBody>() { 323 @Override 324 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 325 try { 326 showResult("onResponse" + response.body().string()); 327 } catch (IOException e) { 328 e.printStackTrace(); 329 } 330 } 331 332 @Override 333 public void onFailure(Call<ResponseBody> call, Throwable t) { 334 showResult("onFailure" + t.getMessage()); 335 } 336 }); 337 } 338 339 private void get7() { 340 // String baseUrl = "http://v5.pc.duomi.com/search-ajaxsearch-searchall?kw=liedehua&pi=1&pz=10"; 341 String baseUrl = "http://v5.pc.duomi.com/"; 342 new Retrofit.Builder() 343 .baseUrl(baseUrl) 344 .client(okHttpClient) 345 .build() 346 .create(NetService.class) 347 .getSearchByPost(new HashMap<String, String>() { 348 { 349 put("kw", "liedehua"); 350 put("pi", "1"); 351 put("pz", "15"); 352 } 353 }).enqueue(new Callback<ResponseBody>() { 354 @Override 355 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 356 try { 357 showResult("onResponse" + response.body().string()); 358 } catch (IOException e) { 359 e.printStackTrace(); 360 } 361 } 362 363 @Override 364 public void onFailure(Call<ResponseBody> call, Throwable t) { 365 showResult("onFailure" + t.getMessage()); 366 } 367 }); 368 } 369 370 private void get6() { 371 // String baseUrl = "http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"; 372 String baseUrl = "http://cache.video.iqiyi.com/"; 373 new Retrofit.Builder() 374 .baseUrl(baseUrl) 375 .client(okHttpClient) 376 .build() 377 .create(NetService.class) 378 .getJpByPost("jsonp9") 379 .enqueue(new Callback<ResponseBody>() { 380 @Override 381 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 382 try { 383 showResult("onResponse" + response.body().string()); 384 } catch (IOException e) { 385 e.printStackTrace(); 386 } 387 } 388 389 @Override 390 public void onFailure(Call<ResponseBody> call, Throwable t) { 391 showResult("onFailure" + t.getMessage()); 392 } 393 }); 394 395 } 396 397 private void get4() { 398 String baseUrl = "http://api.immedc.com/"; 399 new Retrofit.Builder() 400 .baseUrl(baseUrl) 401 .client(okHttpClient) 402 .build() 403 .create(NetService.class) 404 .getStartBannerResponseBody() 405 .enqueue(new Callback<ResponseBody>() { 406 @Override 407 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 408 try { 409 showResult("onResponse" + response.body().string()); 410 } catch (IOException e) { 411 e.printStackTrace(); 412 } 413 } 414 415 @Override 416 public void onFailure(Call<ResponseBody> call, Throwable t) { 417 showResult("onFailure" + t.getMessage()); 418 } 419 }); 420 421 } 422 423 private void get5() { 424 final String baseUrl = "http://www.weather.com.cn/"; 425 new Thread(new Runnable() { 426 @Override 427 public void run() { 428 try { 429 final Weather weather = new Retrofit.Builder() 430 .baseUrl(baseUrl) 431 .addConverterFactory(GsonConverterFactory.create()) 432 .client(okHttpClient) 433 .build() 434 .create(NetService.class) 435 .getWeather() 436 .execute().body(); 437 MainActivity.this.runOnUiThread(new Runnable() { 438 @Override 439 public void run() { 440 showResult(weather.toString()); 441 } 442 }); 443 } catch (IOException e) { 444 e.printStackTrace(); 445 } 446 } 447 }).start(); 448 } 449 450 private void get3() { 451 String baseUrl = "http://www.weather.com.cn/"; 452 // String url = "http://www.weather.com.cn/data/sk/101010100.html"; 453 String url = "data/sk/101010100.html"; 454 new Retrofit.Builder().baseUrl(baseUrl) 455 .client(okHttpClient) 456 .addConverterFactory(GsonConverterFactory.create()) 457 .build() 458 .create(NetService.class) 459 .getWeather(url) 460 .enqueue(new Callback<Weather>() { 461 @Override 462 public void onResponse(Call<Weather> call, Response<Weather> response) { 463 showResult("onResponse" + response.body().toString()); 464 } 465 466 @Override 467 public void onFailure(Call<Weather> call, Throwable t) { 468 showResult("onFailure" + t.getMessage()); 469 } 470 }); 471 } 472 473 private void get2() { 474 String baseUrl = "http://www.kuaidi100.com/"; 475 new Retrofit.Builder() 476 .baseUrl(baseUrl) 477 .client(okHttpClient) 478 .addConverterFactory(GsonConverterFactory.create()) 479 .build().create(NetService.class) 480 .getQueryInfo(new HashMap<String, String>() { 481 { 482 put("type", "yuantong"); 483 put("postid", "500379523313"); 484 } 485 }).enqueue(new Callback<QueryInfo>() { 486 @Override 487 public void onResponse(Call<QueryInfo> call, Response<QueryInfo> response) { 488 showResult("onResponse" + response.body().toString()); 489 } 490 491 @Override 492 public void onFailure(Call<QueryInfo> call, Throwable t) { 493 showResult("onResponse" + t.getMessage()); 494 } 495 }); 496 } 497 498 private void get1() { 499 String baseUrl = "http://m2.qiushibaike.com/"; 500 new Retrofit.Builder().baseUrl(baseUrl) 501 .addConverterFactory(GsonConverterFactory.create()) 502 .client(okHttpClient) 503 .build() 504 .create(NetService.class) 505 .getArticles("latest", 1) 506 .enqueue(new Callback<QiushiModel>() { 507 @Override 508 public void onResponse(Call<QiushiModel> call, Response<QiushiModel> response) { 509 showResult("onResponse" + response.body().toString()); 510 } 511 512 @Override 513 public void onFailure(Call<QiushiModel> call, Throwable t) { 514 showResult("onFailure" + t.getMessage()); 515 } 516 }); 517 } 518 519 private void get0() { 520 String url = "http://www.weather.com.cn/"; 521 Retrofit.Builder builder = new Retrofit.Builder(); 522 builder.baseUrl(url) 523 .client(okHttpClient) 524 .addConverterFactory(GsonConverterFactory.create()) 525 .build().create(NetService.class).getWeather().enqueue(new Callback<Weather>() { 526 @Override 527 public void onResponse(Call<Weather> call, Response<Weather> response) { 528 Weather body = response.body(); 529 showResult(body.toString()); 530 } 531 532 @Override 533 public void onFailure(Call<Weather> call, Throwable t) { 534 showResult(t.getMessage()); 535 } 536 }); 537 } 538 539 private void showResult(String result) { 540 String mResult = itemName + result; 541 tv_content.setText(mResult); 542 Toast.makeText(this, mResult, Toast.LENGTH_SHORT).show(); 543 Log.i(TAG, mResult); 544 } 545 }
建立接口,用於存放網絡請求的方法
1 public interface NetService { 2 3 @GET("data/sk/101010100.html") 4 Call<Weather> getWeather(); 5 6 @GET("article/list/{type}?") 7 Call<QiushiModel> getArticles(@Path("type") String type, @Query("page") int page); 8 9 @GET("query") 10 Call<QueryInfo> getQueryInfo(@QueryMap Map<String, String> map); 11 12 @GET 13 Call<Weather> getWeather(@Url String url); 14 15 @GET("/restapi/loading/getStartBanner") 16 Call<ResponseBody> getStartBannerResponseBody(); 17 18 @FormUrlEncoded 19 @POST("jp/avlist/202861101/1/") 20 Call<ResponseBody> getJpByPost(@Field("callback") String callback); 21 22 @FormUrlEncoded 23 @POST("search-ajaxsearch-searchall") 24 Call<ResponseBody> getSearchByPost(@FieldMap Map<String, String> map); 25 26 @Multipart 27 @POST("MyUploadServer/servlet/UpLoadFileServlet") 28 Call<ResponseBody> postUpLoadFile(@Part() MultipartBody.Part requestBody); 29 30 @POST("MyUploadServer/servlet/MyUploadServlet") 31 Call<ResponseBody> uploadFilesByody(@Body MultipartBody multipartBody); 32 33 @Multipart 34 @POST("MyUploadServer/servlet/MyUploadServlet") 35 Call<ResponseBody> uploadFilesByPart(@Part() List<MultipartBody.Part> parts); 36 37 @Multipart 38 @POST("MyUploadServer/servlet/MyUploadServlet") 39 Call<ResponseBody> uploadFilesByPartMap(@PartMap() Map<String, RequestBody> map); 40 41 @Streaming 42 @GET 43 Call<ResponseBody> download(@Url String fileUrl); 44 45 }