Retrofit网络访问框架的学习
Posted 代码库存
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Retrofit网络访问框架的学习相关的知识,希望对你有一定的参考价值。
Retrofit具体使用方法
1 import android.app.AlertDialog; 2 import android.content.DialogInterface; 3 import android.os.Bundle; 4 import android.os.Environment; 5 import android.os.Handler; 6 import android.support.v7.app.AppCompatActivity; 7 import android.util.Log; 8 import android.view.View; 9 import android.widget.TextView; 10 import android.widget.Toast; 11 12 import com.example.okhttputils.OkHttpClientManager; 13 14 import java.io.File; 15 import java.io.FileOutputStream; 16 import java.io.IOException; 17 import java.io.InputStream; 18 import java.io.OutputStream; 19 import java.util.ArrayList; 20 import java.util.HashMap; 21 import java.util.List; 22 23 import okhttp3.MultipartBody; 24 import okhttp3.OkHttpClient; 25 import okhttp3.RequestBody; 26 import okhttp3.ResponseBody; 27 import retrofit2.Call; 28 import retrofit2.Callback; 29 import retrofit2.Response; 30 import retrofit2.Retrofit; 31 import retrofit2.converter.gson.GsonConverterFactory; 32 33 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 34 35 private TextView tv_content; 36 private String TAG = this.getClass().getSimpleName(); 37 private String itemName; 38 private String STR_TAG = TAG + "--->***"; 39 protected OkHttpClient okHttpClient; 40 protected Handler deliveryHandler; 41 42 @Override 43 protected void onCreate(Bundle savedInstanceState) { 44 super.onCreate(savedInstanceState); 45 setContentView(R.layout.activity_main); 46 findViewById(R.id.btn_retrofit).setOnClickListener(this); 47 tv_content = (TextView) findViewById(R.id.tv_content); 48 49 okHttpClient = OkHttpClientManager.getInstance(this).getOkHttpClient(); 50 deliveryHandler = OkHttpClientManager.getInstance(MainActivity.this).getDeliveryHandler(); 51 } 52 53 @Override 54 public void onClick(View v) { 55 //弹一个对话框,分类选择: 56 show(); 57 58 } 59 60 private void show() { 61 //创建builder对象。 62 final AlertDialog.Builder builder = new AlertDialog.Builder(this); 63 //设置标题. 64 builder.setTitle("Retrofit2操作"); 65 //设置列表内容,以及点击事件. 66 //参数:1,String数组.2,点击事件. 67 final String[] items = { 68 "0指定无参数GET请求", 69 "1指定@Path和@Query参数GET请求", 70 "2指定@QueryMap参数集合GET请求", 71 "3指定@Url参数GET请求", 72 "4指定GET请求返回ResponseBody", 73 "5同步GET请求", 74 "6指定@Fild参数POST请求", 75 "7指定@FildMap参数POST请求", 76 "8指定@Part参数单文件上传", 77 "9指定@Body多文件上传带参数", 78 "10指定@Part通过多文件上传带参数", 79 "11指定@PartMap多文件上传带参数", 80 "12指定@Streaming大文件下载", 81 }; 82 builder.setItems(items, new DialogInterface.OnClickListener() { 83 @Override 84 public void onClick(DialogInterface dialogInterface, int i) { 85 itemName = items[i] + STR_TAG; 86 switch (i) { 87 case 0: 88 get0(); 89 break; 90 case 1: 91 get1(); 92 break; 93 case 2: 94 get2(); 95 break; 96 case 3: 97 get3(); 98 break; 99 case 4: 100 get4(); 101 break; 102 case 5: 103 get5(); 104 break; 105 case 6: 106 get6(); 107 break; 108 case 7: 109 get7(); 110 break; 111 case 8: 112 get8(); 113 break; 114 case 9: 115 get9(); 116 break; 117 case 10: 118 get10(); 119 break; 120 case 11: 121 get11(); 122 break; 123 case 12: 124 get12(); 125 break; 126 } 127 } 128 }); 129 builder.create().show(); 130 } 131 132 private void get11() { 133 final File file = new File(Environment.getExternalStorageDirectory(), "1.txt"); 134 final File file1 = new File(Environment.getExternalStorageDirectory(), "2.png"); 135 final RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 136 final RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 137 final RequestBody body2 =RequestBody.create(MultipartBody.FORM, "zxn001"); 138 139 // body =MultipartBody.Part.createFormData("file", file.getName(), body).body(); 140 // body1 =MultipartBody.Part.createFormData("file", file.getName(), body1).body(); 141 // final RequestBody body2 = MultipartBody.Part.createFormData("username", "zxn001").body(); 142 143 144 String baseUrl = "http://192.168.1.102/"; 145 new Retrofit.Builder() 146 .baseUrl(baseUrl) 147 .client(okHttpClient) 148 .build() 149 .create(NetService.class) 150 .uploadFilesByPartMap(new HashMap<String, RequestBody>(){ 151 { 152 put("file\"; filename=\""+file.getName(), body); 153 put("file\"; filename=\""+file1.getName(), body1); 154 put("username",body2); 155 } 156 }) 157 .enqueue(new Callback<ResponseBody>() { 158 @Override 159 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 160 try { 161 showResult("onResponse"+response.body().string()); 162 } catch (IOException e) { 163 e.printStackTrace(); 164 } 165 } 166 167 @Override 168 public void onFailure(Call<ResponseBody> call, Throwable t) { 169 showResult("onFailure"+t.getMessage()); 170 } 171 }); 172 } 173 174 private void get12() { 175 final String baseUrl = "http://1251603248.vod2.myqcloud.com/"; 176 final String downUrl = "http://1251603248.vod2.myqcloud.com/4c9adaa7vodtransgzp1251603248/30e0819d9031868223192061218/v.f40.mp4"; 177 new Thread(new Runnable() { 178 @Override 179 public void run() { 180 try { 181 Response<ResponseBody> response = new Retrofit.Builder() 182 .baseUrl(baseUrl) 183 .client(okHttpClient) 184 .build() 185 .create(NetService.class) 186 .download(downUrl) 187 .execute(); 188 189 if (response.isSuccessful()) { 190 deliveryHandler.post(new Runnable() { 191 @Override 192 public void run() { 193 showResult("服务器连接成功!"); 194 } 195 }); 196 boolean ok = writeDisk(response.body()); 197 Log.i(TAG, STR_TAG + "run: 下载:" + ok); 198 if (ok) { 199 deliveryHandler.post(new Runnable() { 200 @Override 201 public void run() { 202 tv_content.setText("下载完成!!"); 203 } 204 }); 205 } 206 } else { 207 deliveryHandler.post(new Runnable() { 208 @Override 209 public void run() { 210 showResult("下载失败!"); 211 } 212 }); 213 } 214 } catch (IOException e) { 215 e.printStackTrace(); 216 } 217 } 218 }).start(); 219 } 220 221 private boolean writeDisk(ResponseBody body) { 222 try { 223 File file = new File(Environment.getExternalStorageDirectory(), "1.mp4"); 224 InputStream inputStream = null; 225 OutputStream outputStream = null; 226 try { 227 byte[] fileReader = new byte[4096]; 228 long fileSize = body.contentLength(); 229 long loadSize = 0; 230 231 inputStream = body.byteStream(); 232 outputStream = new FileOutputStream(file); 233 int len = -1; 234 while ((len = inputStream.read(fileReader)) != -1) { 235 outputStream.write(fileReader, 0, len); 236 loadSize += len; 237 Log.i(TAG, STR_TAG + "已经下载: " + loadSize + "/总大小: " + fileSize); 238 } 239 outputStream.flush(); 240 return true; 241 } catch (IOException e) { 242 return false; 243 } finally { 244 if (inputStream != null) { 245 inputStream.close(); 246 } 247 if (outputStream != null) { 248 outputStream.close(); 249 } 250 } 251 } catch (IOException e) { 252 return false; 253 } 254 } 255 256 private void get10() { 257 File file = new File(Environment.getExternalStorageDirectory(), "1.txt"); 258 File file1 = new File(Environment.getExternalStorageDirectory(), "2.png"); 259 List<MultipartBody.Part> parts = new ArrayList<>(); 260 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 261 RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 262 MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body); 263 MultipartBody.Part part1 = MultipartBody.Part.createFormData("file", file1.getName(), body1); 264 MultipartBody.Part part2 = MultipartBody.Part.createFormData("username", "zxn001"); 265 parts.add(part); 266 parts.add(part1); 267 parts.add(part2); 268 269 // String baseUrl = "http://192.168.1.102/"; 270 String baseUrl = "http://169.254.38.24/"; 271 new Retrofit.Builder() 272 .baseUrl(baseUrl) 273 .client(okHttpClient) 274 .build() 275 .create(NetService.class) 276 .uploadFilesByPart(parts) 277 .enqueue(new Callback<ResponseBody>() { 278 @Override 279 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 280 try { 281 showResult("onResponse" + response.body().string()); 282 } catch (IOException e) { 283 e.printStackTrace(); 284 } 285 } 286 287 @Override 288 public void onFailure(Call<ResponseBody> call, Throwable t) { 289 showResult("onFailure" + t.getMessage()); 290 } 291 }); 292 } 293 294 private void get9() { 295 File file = new File(Environment.getExternalStorageDirectory(), "a.jpg"); 296 File file1 = new File(Environment.getExternalStorageDirectory(), "d.jpg"); 297 MultipartBody.Builder builder = new MultipartBody.Builder(); 298 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 299 RequestBody body1 = MultipartBody.create(MultipartBody.FORM, file1); 300 MultipartBody multipartBody = builder 301 .addFormDataPart("file", file.getName(), body) 302 .addFormDataPart("file", file1.getName(), body1) 303 .addFormDataPart("username", "zxn123") 304 .setType(MultipartBody.FORM) 305 .build(); 306 307 // String baseUrl = "http://192.168.1.102/"; 308 String baseUrl = "http://169.254.38.24/"; 309 new Retrofit.Builder() 310 .baseUrl(baseUrl) 311 .client(okHttpClient) 312 .build() 313 .create(NetService.class) 314 .uploadFilesByody(multipartBody) 315 .enqueue(new Callback<ResponseBody>() { 316 @Override 317 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 318 try { 319 showResult("onResponse" + response.body().string()); 320 } catch (IOException e) { 321 e.printStackTrace(); 322 } 323 } 324 325 @Override 326 public void onFailure(Call<ResponseBody> call, Throwable t) { 327 showResult("onFailure" + t.getMessage()); 328 } 329 }); 330 331 } 332 333 private void get8() { 334 //指定上传文件 335 File file = new File(Environment.getExternalStorageDirectory(), "3.jpg"); 336 // RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file); 337 338 //封装请求体 339 // RequestBody body = RequestBody.create(MediaType.parse("application/otcet-stream"), file); 340 RequestBody body = MultipartBody.create(MultipartBody.FORM, file); 341 MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), body); 342 343 344 //http://192.168.1.100/MyUploadServer/servlet/UpLoadFileServlet 345 // String baseUrl = "http://192.168.1.102/"; 346 String baseUrl = "http://169.254.38.24/"; 347 348 new Retrofit.Builder() 349 .baseUrl(baseUrl) 350 .client(okHttpClient) 351 .build() 352 .create(NetService.class) 353 .postUpLoadFile(part) 354 .enqueue(new Callback<ResponseBody>() { 355 @Override 356 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 357 try { 358 showResult("onResponse" + response.body().string()); 359 } catch (IOException e) { 360 e.printStackTrace(); 361 } 362 } 363 364 @Override 365 public void onFailure(Call<ResponseBody> call, Throwable t) { 366 showResult("onFailure" + t.getMessage()); 367 } 368 }); 369 } 370 371 private void get7() { 372 // String baseUrl = "http://v5.pc.duomi.com/search-ajaxsearch-searchall?kw=liedehua&pi=1&pz=10"; 373 String baseUrl = "http://v5.pc.duomi.com/"; 374 new Retrofit.Builder() 375 .baseUrl(baseUrl) 376 .client(okHttpClient) 377 .build() 378 .create(NetService.class) 379 .getSearchByPost(new HashMap<String, String>() { 380 { 381 put("kw", "liedehua"); 382 put("pi", "1"); 383 put("pz", "15"); 384 } 385 }).enqueue(new Callback<ResponseBody>() { 386 @Override 387 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 388 try { 389 showResult("onResponse" + response.body().string()); 390 } catch (IOException e) { 391 e.printStackTrace(); 392 } 393 } 394 395 @Override 396 public void onFailure(Call<ResponseBody> call, Throwable t) { 397 showResult("onFailure" + t.getMessage()); 398 } 399 }); 400 } 401 402 private void get6() { 403 // String baseUrl = "http://cache.video.iqiyi.com/jp/avlist/202861101/1/?callback=jsonp9"; 404 String baseUrl = "http://cache.video.iqiyi.com/"; 405 new Retrofit.Builder() 406 .baseUrl(baseUrl) 407 .client(okHttpClient) 408 .build() 409 .create(NetService.class) 410 .getJpByPost("jsonp9") 411 .enqueue(new Callback<ResponseBody>() { 412 @Override 413 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 414 try { 415 showResult("onResponse" + response.body().string()); 416 } catch (IOException e) { 417 e.printStackTrace(); 418 } 419 } 420 421 @Override 422 public void onFailure(Call<ResponseBody> call, Throwable t) { 423 showResult("onFailure" + t.getMessage()); 424 } 425 }); 426 427 } 428 429 private void get4() { 430 String baseUrl = "http://api.immedc.com/"; 431 new Retrofit.Builder() 432 .baseUrl(baseUrl) 433 .client(okHttpClient) 434 .build() 435 .create(NetService.class) 436 .getStartBannerResponseBody() 437 .enqueue(new Callback<ResponseBody>() { 438 @Override 439 public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { 440 try { 441 showResult("onResponse" + response.body().string()); 442 } catch (IOException e) { 443 e.printStackTrace(); 444 } 445 } 446 447 @Override 448 public void onFailure(Call<ResponseBody> call, Throwable t) { 449 showResult("onFailure" + t.getMessage()); 450 } 451 }); 452 453 } 454 455 private void get5() { 456 final String baseUrl = "http://www.weather.com.cn/"; 457 new Thread(new Runnable() { 458 @Override 459 public void run() { 460 try { 461 final Weather weather = new Retrofit.Builder() 462 .baseUrl(baseUrl) 463 .addConverterFactory(GsonConverterFactory.create()) 464 .client(okHttpClient) 465 .build() 466 .create(NetService.class) 467 .getWeather() 468 .execute().body(); 469 MainActivity.this.runOnUiThread(new Runnable() { 470 @Override 471 public void run() { 472 showResult(weather.toString()); 473 } 474 }); 475 } catch (IOException e) { 476 e.printStackTrace(); 477 } 478 } 479 }).start(); 480 } 481 482 private void get3() { 483 String baseUrl = "http://www.weather.com.cn/"; 484 // String url = "http://www.weather.com.cn/data/sk/101010100.html"; 485 String url = "data/sk/101010100.html"; 486 new Retrofit.Builder().baseUrl(baseUrl) 487 .client(okHttpClient) 488 .addConverterFactory(GsonConverterFactory.create()) 489 .build() 490 .create(NetService.class) 491 .getWeather(url) 492 .enqueue(new Callback<Weather>() { 493 @Override 494 public void onResponse(Call<Weather> call, Response<Weather> response) { 495 showResult("onResponse" + response.body().toString()); 496 } 497 498 @Override 499 public void onFailure(Call<Weather> call, Throwable t) { 500 showResult("onFailure" + t.getMessage()); 501 } 502 }); 503 } 504 505 private void get2() { 506 String baseUrl = "http://www.kuaidi100.com/"; 507 new Retrofit.Builder() 508 .baseUrl(baseUrl) 509 .client(okHttpClient) 510 .addConverterFactory(GsonConverterFactory.create()) 511 .build().create(NetService.class) 512 .getQueryInfo(new HashMap<String, String>() { 513 { 514 put("type", "yuantong"); 515 put("postid", "500379523313"); 516 } 517 }).enqueue(new Callback<QueryInfo>() { 518 @Override 519 public void onResponse(Call<QueryInfo> call, Response<QueryInfo> response) { 520 showResult("onResponse" + response.body().toString()); 521 } 522 523 @Override 524 public void onFailure(Call<QueryInfo> call, Throwable t) { 525 showResult("onResponse" + t.getMessage()); 526 } 527 }); 528 } 529 530 private void get1() { 531 String baseUrl = "http://m2.qiushibaike.com/"; 532 new Retrofit.Builder().baseUrl(baseUrl) 533 .addConverterFactory(GsonConverterFactory.create()) 534 .client(okHttpClient) 535 .build() 536 .create(NetService.class) 537 .getArticles("latest", 1) 538 .enqueue(new Callback<QiushiModel>() { 539 @Override 540 public void onResponse(Call<QiushiModel> call, Response<QiushiModel> response) { 541 showResult("onResponse" + response.body().toString()); 542 } 543 544 @Override 545 public void onFailure(Call<QiushiModel> call, Throwable t) { 546 showResult("onFailure" + t.getMessage()); 547 } 548 }); 549 } 550 551 private void get0() { 552 String url = "http://www.weather.com.cn/"; 553 Retrofit.Builder builder = new Retrofit.Builder(); 554 builder.baseUrl(url) 555 .client(okHttpClient) 556 .addConverterFactory(GsonConverterFactory.create()) 557 .build().create(NetService.class).getWeather().enqueue(new Callback<Weather>() { 558 @Override 559 public void onResponse(Call<Weather> call, Response<Weather> response) { 560 Weather body = response.body(); 561 showResult(body.toString()); 562 } 563 564 @Override 565 public void onFailure(Call<Weather> call, Throwable t) { 566 showResult(t.getMessage()); 567 } 568 }); 569 } 570 571 private void showResult(String result) { 572 String mResult = itemName + result; 573 tv_content.setText(mResult); 574 Toast.makeText(this, mResult, Toast.LENGTH_SHORT).show(); 575 Log.i(TAG, mResult); 576 } 577 }
自定义接口方法,用于存放网络请求方法
1 import java.util.List; 2 import java.util.Map; 3 4 import okhttp3.MultipartBody; 5 import okhttp3.RequestBody; 6 import okhttp3.ResponseBody; 7 import retrofit2.Call; 8 import retrofit2.http.Body; 9 import retrofit2.http.Field; 10 import retrofit2.http.FieldMap; 11 import retrofit2.http.FormUrlEncoded; 12 import retrofit2.http.GET; 13 import retrofit2.http.Multipart; 14 import retrofit2.http.POST; 15 import retrofit2.http.Part; 16 import retrofit2.http.PartMap; 17 import retrofit2.http.Path; 18 import retrofit2.http.Query; 19 import retrofit2.http.QueryMap; 20 import retrofit2.http.Streaming; 21 import retrofit2.http.Url; 22 23 /** 24 * 创建接口,用于存放网络请求的方法。 25 */ 26 27 public interface NetService { 28 29 @GET("data/sk/101010100.html") 30 Call<Weather> getWeather(); 31 32 @GET("article/list/{type}?") 33 Call<QiushiModel> getArticles(@Path("type") String type, @Query("page") int page); 34 35 @GET("query") 36 Call<QueryInfo> getQueryInfo(@QueryMap Map<String, String> map); 37 38 @GET 39 Call<Weather> getWeather(@Url String url); 40 41 @GET("/restapi/loading/getStartBanner") 42 Call<ResponseBody> getStartBannerResponseBody(); 43 44 @FormUrlEncoded 45 @POST("jp/avlist/202861101/1/") 46 Call<ResponseBody> getJpByPost(@Field("callback") String callback); 47 48 @FormUrlEncoded 49 @POST("search-ajaxsearch-searchall") 50 Call<ResponseBody> getSearchByPost(@FieldMap Map<String, String> map); 51 52 @Multipart 53 @POST("MyUploadServer/servlet/UpLoadFileServlet") 54 Call<ResponseBody> postUpLoadFile(@Part() MultipartBody.Part requestBody); 55 56 @POST("MyUploadServer/servlet/MyUploadServlet") 57 Call<ResponseBody> uploadFilesByody(@Body MultipartBody multipartBody); 58 59 @Multipart 60 @POST("MyUploadServer/servlet/MyUploadServlet") 61 Call<ResponseBody> uploadFilesByPart(@Part() List<MultipartBody.Part> parts); 62 63 @Multipart 64 @POST("MyUploadServer/servlet/MyUploadServlet") 65 Call<ResponseBody> uploadFilesByPartMap(@PartMap() Map<String, RequestBody> map); 66 67 @Streaming 68 @GET 69 Call<ResponseBody> download(@Url String fileUrl); 70 71 }
需要写一个网络访问数据的解析类就可以使用了
在清单中加入权限
1 <uses-permission android:name="android.permission.INTERNET"/> 2 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 3 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
在build中加入依赖
1 compile ‘com.squareup.retrofit2:retrofit:2.3.0‘ 2 // compile ‘com.squareup.okhttp3:okhttp:3.8.1‘ 3 compile ‘com.squareup.retrofit2:converter-gson:2.0.2‘ 4 compile project(‘:library-okhttputils‘)
以上是关于Retrofit网络访问框架的学习的主要内容,如果未能解决你的问题,请参考以下文章
基于Retrofit+RxJava的Android分层网络请求框架