Retrofit + Rxjava框架学习使用(举例:酷狗搜索和详情接口)

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_35584878/article/details/90716208

在我上一篇博客Retrofit框架简单学习使用基础上修改。

 

  依赖:

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'// Retrofit库
    implementation "com.squareup.retrofit2:converter-gson:2.5.0"// gson库
    //在原来Retrofit框架学习的基础上加上下面的Rxjava依赖:
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.5.0"
    implementation "io.reactivex.rxjava2:rxjava:2.0.1"
    implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
  }

  权限:

 

<uses-permission android:name="android.permission.INTERNET"/>

 

  接口:

a、酷狗的搜索:http://mobilecdn.kugou.com/api/v3/search/song?format=json&keyword=歌名&page=1&pagesize=20

b、酷狗歌曲详情:http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=上面搜索的歌曲的hash值

 

  实体:

搜索接口返回数据的实体:

public class KugouSearch {


    /**
     * status : 1
     * error :
     * data : {"info":[{"filesize":4112080,"bitrate":128,"price":200,"songname_original":"尽头","singername":"赵方婧","filename":"赵方婧 - 尽头","price_320":200,"songname":"尽头","hash":"73f211b375593a4332bb5e4a28602c61","mvhash":"237f68e950df010c12426a2d50dc3b3e","duration":256,"album_name":"尽头"}],"total":442}
     * errcode : 0
     */

    private int status;
    private String error;
    private DataBean data;
    private int errcode;

    //此处省略get、set方法,读者自行补上

    public static class DataBean {
        /**
         * info : [{"filesize":4112080,"bitrate":128,"price":200,"songname_original":"尽头","singername":"赵方婧","filename":"赵方婧 - 尽头","songname":"尽头","hash":"73f211b375593a4332bb5e4a28602c61","mvhash":"237f68e950df010c12426a2d50dc3b3e","duration":256,"album_name":"尽头"}]
         * total : 442
         */

        private int total;
        private List<InfoBean> info;

        //此处省略get、set方法,读者自行补上

        public static class InfoBean {
            /**
             * filesize : 4112080
             * price : 200
             * singername : 赵方婧
             * filename : 赵方婧 - 尽头
             * songname : 尽头
             * hash : 73f211b375593a4332bb5e4a28602c61
             * mvhash : 237f68e950df010c12426a2d50dc3b3e
             * duration : 256
             * album_name : 尽头
             */

            private int filesize;
            private int price;
            private String singername;
            private String filename;
            private String songname;
            private String hash;
            private String mvhash;
            private int duration;
            private String album_name;

            //此处省略get、set方法,读者自行补上

            //注意此处toString方法返回的值是给ArrayList列表显示String值用,直接传对象进去即可
            @Override
            public String toString() {
                return getFilename();
            }
        }
    }

}

酷狗音乐详情实体: 

public class KugouDetail {

    /**
     * fileSize : 3198974
     * album_img : http://imge.kugou.com/stdmusic/{size}/20161109/20161109171040932108.jpg
     * url : http://fs.open.kugou.com/b581ce50f62a906c2d87d1ea52e8a20f/5ce2167f/G078/M08/18/17/jg0DAFgi6G-AKqsqADDP_nSW5F4051.mp3
     * time : 1558321463
     * singerName : 李玉刚
     * songName : 刚好遇见你
     * hash : CB7EE97F4CC11C4EA7A1FA4B516A5D97
     * error :
     * imgUrl : http://singerimg.kugou.com/uploadpic/softhead/{size}/20181224/20181224183453372.jpg
     * status : 1
     * singerId : 2018
     * fileName : 李玉刚 - 刚好遇见你
     * errcode : 0
     * timeLength : 200
     */

    private int fileSize;
    private String album_img;
    private String url;
    private long time;
    private String singerName;
    private String songName;
    private String hash;
    private String error;
    private String imgUrl;
    private int status;
    private int singerId;
    private String fileName;
    private int errcode;
    private int timeLength;

    //get、set方法我就不列出来了……
}

 

接下来就是Retrofit+Rxjava框架主要的代码了:

 

抽象接口类(把原来Call<KugouSearch>改成Observable<KugouSearch>):

public interface RequestInterface {

    //第一个为搜索接口
   @GET("song?format=json")
   Observable<KugouSearch> searchKugou(@QueryMap Map<String,Object> map);
    
    //第二个为歌曲详情接口
   @FormUrlEncoded
   @POST("getSongInfo.php?cmd=playInfo")
  Observable<KugouDetail> getDetail(@Field("hash") String hash);
}

 

 

 acivity中调用搜索方法(1、原来基础上加上rxjava支持;2、改用rxjava方式调用接口和回调响应):

//用Retrofit拿到RequestInterface类的实体
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://mobilecdn.kugou.com/api/v3/search/")
        .addConverterFactory(GsonConverterFactory.create())
        //原来基础上加上rxjava支持
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);

//封装数据依旧
Map<String,Object> map = new HashMap(3);
map.put("keyword","最爱");
map.put("page",1);
map.put("pagesize",10);

//调用接口方法
requestInterface.searchKugou(map)
        .subscribeOn(Schedulers.io()) //接口方法io线程中执行(网络线程)
        .observeOn(AndroidSchedulers.mainThread()) //下面的回调方法在主线程中执行
        .subscribe(new Observer<KugouSearch>() {

            @Override
            public void onError(Throwable e) {
                Log.e("myout", "onFailure: "+e.getMessage());
                Toast.makeText(MainActivity.this, "连接失败:"+e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(KugouSearch kugouSearch) {
                if(kugouSearch.getData()!=null&&kugouSearch.getData().getInfo()!=null){
                    list = kugouSearch.getData().getInfo();
                    ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,list);
                    listView.setAdapter(adapter);
                }else{
                    Toast.makeText(MainActivity.this, "没有数据", Toast.LENGTH_SHORT).show();
                }
            }
        });
});

获取详情的方法,同理:

//http://m.kugou.com/app/i/getSongInfo.php?cmd=playInfo&hash=CB7EE97F4CC11C4EA7A1FA4B516A5D97
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://m.kugou.com/app/i/")
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .build();
RequestInterface requestInterface = retrofit.create(RequestInterface.class);
requestInterface.getDetail(list.get(position).getHash())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Observer<KugouDetail>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(KugouDetail kugouDetail) {
                if(kugouDetail.getErrcode() == 0){
                    View detailView = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog_detail,null);
                    ((TextView)detailView.findViewById(R.id.song)).setText(kugouDetail.getSongName());
                    ((TextView)detailView.findViewById(R.id.singer)).setText(kugouDetail.getSingerName());
                    ((TextView)detailView.findViewById(R.id.filesize)).setText(String.valueOf(kugouDetail.getFileSize()));
                    ((TextView)detailView.findViewById(R.id.time)).setText(String.valueOf(kugouDetail.getTimeLength()));
                    ((TextView)detailView.findViewById(R.id.hash)).setText(kugouDetail.getHash());
                    ((TextView)detailView.findViewById(R.id.url)).setText(kugouDetail.getUrl());
                    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                    dialog.setTitle("详情");
                    dialog.setView(detailView);
                    dialog.setPositiveButton("关闭",null);
                    dialog.show();
                }else{
                    Toast.makeText(MainActivity.this, "错误码:"+kugouDetail.getErrcode(), Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(MainActivity.this, "获取失败:"+e.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete() {

            }
        });

 最后附上地址:

GitHub

 

 

展开阅读全文

没有更多推荐了,返回首页