Android使用Retrofit+OkHttp实现网络请求

    xiaoxiao2021-03-25  125

    开篇话: 写这篇文章,是因为这种方式越来越受开发者青睐,而且大谷歌也不维护volley了,同时,也是因为网上的不少文章介绍不是很平易化,像我这样没有多少底的程序员是看不懂的,大神们也不要笑话我这篇文章,毕竟,我也希望初学者更容易入手。。。

    首先,引入依赖。别跟我说你还用Eclipse开发。

    compile 'com.squareup.retrofit2:retrofit:2.2.0' compile 'com.squareup.retrofit2:retrofit-adapters:2.2.0' compile 'com.squareup.okhttp3:okhttp:3.6.0' compile 'com.packetzoom:pz-okhttp3-interceptor:3.2.25' compile 'com.squareup.retrofit2:converter-gson:2.2.0'

    首先,建议先创建实体,这个实体是用来解析你的数据的。下面我贴上我的代码:说明一下,我有两个实体,因为有一个接口不支持post请求,所以有点尴尬,就弄了两个接口来

    public class WeiXinBean { public ResultBean showapi_res_body; public int showapi_res_code; public String showapi_res_error; public class ResultBean { public int code; public String msg; public List<WeiXin> newslist = new ArrayList<>(); public class WeiXin { public String ctime; public String description; public String picUrl; public String title; public String url; } } } //-------------------------------------------------------不华丽的分割线 public class VideoBean { public String avatar; public String caption; public long comments_count; public String cover_pic; public long id; public long likes_count; public long plays_count; public String screen_name; public String url; }

    然后,开始定义一个服务接口,用来管理网络请求,看代码:

    public interface VideoApiService { @POST("/181-1") @FormUrlEncoded Call<WeiXinBean> showDataByPost(@Field("showapi_appid") String showapi_appid, @Field("showapi_sign") String showapi_sign, @Field("num") String num); @GET("/output/channels_topics_timeline.json") Call<List<VideoBean>> showDataByGet(@Query("topic_name") String topic_name, @Query("page")int page); }

    接着,整合OkHttp和Retrofit还是看代码,注释写在post方法中,不理解的可以先去看post方法:

    private final static String BASE_URL_GET = "http://newapi.meipai.com"; private final static String BASE_URL_POST = "http://route.showapi.com"; private void showByGet(){ OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS); final OkHttpClient client = builder.build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL_GET) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); VideoApiService service = retrofit.create(VideoApiService.class); Call<List<VideoBean>> call = service.showDataByGet("热门",1); call.enqueue(new Callback<List<VideoBean>>() { @Override public void onResponse(Call<List<VideoBean>> call, Response<List<VideoBean>> response) { System.out.println("-------------get------------" + response.body().size()); } @Override public void onFailure(Call<List<VideoBean>> call, Throwable t) { } }); } //---------------------------------------------------------不华丽的分割线 private void showByPOST(){ //配置okhttp参数 OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS); //获取client对象 final OkHttpClient client = builder.build(); //创建Retrofit对象,并建立与okhttp的联系。这里还可以配置拦截器,看你业务需求 Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL_POST) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); //创建请求服务 VideoApiService service = retrofit.create(VideoApiService.class); //发起请求 Call<WeiXinBean> call = service.showDataByPost("20835","703f51e7062e48378ceeee02e2949db8","10"); call.enqueue(new Callback<WeiXinBean>() { @Override public void onResponse(Call<WeiXinBean> call, Response<WeiXinBean> response) { int size = response.body().showapi_res_body.newslist.size(); System.out.println("-------------post------------" + size); } @Override public void onFailure(Call<WeiXinBean> call, Throwable t) { } });

    到这里,基本完成了,封装这种事,这里就不做了,这里给最基本的功能。接下来就是调用这两个方法了。我这里是给了两个button,一个用来get请求,一个用用post请求,点击分别调用方法,代码我就不贴了,如果说给到这里,你还不懂,我只能呵呵了。顺便说一下,之前看到说onResponse方法里是跑在子线程的,不能更新ui,我测试了一些,让它睡了10秒,看一下代码和结果

    public void onResponse(Call<List<VideoBean>> call, Response<List<VideoBean>> response) { System.out.println("-------------get------------" + response.body().size()); SystemClock.sleep(10000); tv_result.setText(response.body().get(0).url); }

    睡了10秒最终更新了ui,如果说不是主线程,应该阻塞然后就报错了呀。还是我现在这个版本比较新呢。。。不知道你们怎么看。。。本来还想说,如果报错了,我就再搞个RxJava上来结合一下,现在看来不用搞先了,以后会补上的。 最后,文章到这里结束了,源码就不上了,比较简单。

    转载请注明原文地址: https://ju.6miu.com/read-6618.html

    最新回复(0)