Retrofit+Rxjava1.0请求数据

这是一篇浅显的Rxjava+Retrofit文章,从初学者出发,感觉如果工作中没有充足发挥自学技能的项目,直接去看大佬们写的很深入的讲解,特别容易遗忘、懵甚至不理解,所以我决定写一篇浅显的使用Rxjava+Retrofit的文章。

我访问的是“聚合数据”提供的新闻头条链接(“http://v.juhe.cn/toutiao/index?type=top&key=28aa4ac2a689c881a4e6e51cf918d695”)

1.添加依赖库

/*retrofit2*/
implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
implementation 'com.squareup.retrofit2:retrofit:2.0.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.okhttp3:okhttp:3.3.0'
implementation 'com.squareup.okio:okio:1.7.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.2.0'
implementation 'io.reactivex:rxandroid:1.1.0'
implementation 'io.reactivex:rxjava:1.1.0'
implementation'com.squareup.retrofit2:retrofit:2.1.0'
implementation'com.squareup.retrofit2:adapter-rxjava:2.1.0'
/*retrofit2*/

2.创建bean(此为请求数据为json的实体类)

import java.util.List;

/**
 * 作者:Android
 * 时间:2018/9/12 15:55
 * 功能:
 */
public class RetrofitRxjavaResult {

    private String reason;//成功的返回
    private ResultBean result;
    private int error_code;

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public ResultBean getResult() {
        return result;
    }

    public void setResult(ResultBean result) {
        this.result = result;
    }

    public int getError_code() {
        return error_code;
    }

    public void setError_code(int error_code) {
        this.error_code = error_code;
    }

    @Override
    public String toString() {
        return "RetrofitRxjavaResult{" +
                "reason='" + reason + '\'' +
                ", result=" + result +
                ", error_code=" + error_code +
                '}';
    }

    public static class ResultBean {

        private String stat;
        private List<DataBean> data;

        public String getStat() {
            return stat;
        }

        public void setStat(String stat) {
            this.stat = stat;
        }

        public List<DataBean> getData() {
            return data;
        }

        public void setData(List<DataBean> data) {
            this.data = data;
        }

        public static class DataBean {

            private String uniquekey;
            private String title;
            private String date;
            private String category;
            private String author_name;
            private String url;
            private String thumbnail_pic_s;
            private String thumbnail_pic_s02;
            private String thumbnail_pic_s03;

            public String getUniquekey() {
                return uniquekey;
            }

            public void setUniquekey(String uniquekey) {
                this.uniquekey = uniquekey;
            }

            public String getTitle() {
                return title;
            }

            public void setTitle(String title) {
                this.title = title;
            }

            public String getDate() {
                return date;
            }

            public void setDate(String date) {
                this.date = date;
            }

            public String getCategory() {
                return category;
            }

            public void setCategory(String category) {
                this.category = category;
            }

            public String getAuthor_name() {
                return author_name;
            }

            public void setAuthor_name(String author_name) {
                this.author_name = author_name;
            }

            public String getUrl() {
                return url;
            }

            public void setUrl(String url) {
                this.url = url;
            }

            public String getThumbnail_pic_s() {
                return thumbnail_pic_s;
            }

            public void setThumbnail_pic_s(String thumbnail_pic_s) {
                this.thumbnail_pic_s = thumbnail_pic_s;
            }

            public String getThumbnail_pic_s02() {
                return thumbnail_pic_s02;
            }

            public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
                this.thumbnail_pic_s02 = thumbnail_pic_s02;
            }

            public String getThumbnail_pic_s03() {
                return thumbnail_pic_s03;
            }

            public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
                this.thumbnail_pic_s03 = thumbnail_pic_s03;
            }
        }
    }
}

3.Retrofit与Rxjava结合的类

package com.example.androidvideo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;

import com.example.androidvideo.R;
import com.example.androidvideo.adpater.MyListViewAdapter;
import com.example.androidvideo.bean.RetrofitRxjavaResult;
import com.example.androidvideo.interfaces.NewsService;
import com.example.androidvideo.utils.LogUtils;
import com.example.androidvideo.utils.ToastUtils;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 作者:Android
 * 时间:2018/9/12 15:51
 * 功能:Retrofit和Rxjava的网络请求
 */
public class RetrofitRxjavaActivity extends Activity {
    private static final String TAG = RetrofitRxjavaActivity.class.getSimpleName();
    private static final long TIMEOUT = 5000;
    private static final String BASE_URL = "http://v.juhe.cn/toutiao/";
    private ListView listView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrorxjava);
        initView();
        requestServer();
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.listView);
    }

    /**
     * 请求网络
     */
    private void requestServer() {
        /*OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {//添加网络访问Header
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("token", "123");
                return chain.proceed(builder.build());
            }
        })
                .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        //获取网络错误信息
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    }
                }).setLevel(HttpLoggingInterceptor.Level.BASIC))
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)//链接超时
                .readTimeout(TIMEOUT, TimeUnit.SECONDS)//读取超时
                .build();*/
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.SECONDS)
                .readTimeout(5000, TimeUnit.SECONDS)
                .build();
        Gson buildGson = new GsonBuilder()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                .create();
        NewsService newsService = new Retrofit.Builder().baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加Rxjava支持
                .addConverterFactory(GsonConverterFactory.create(buildGson))
                .client(okHttpClient)
                .build().create(NewsService.class);
        Observable<RetrofitRxjavaResult> observable = newsService.getNews("top", "28aa4ac2a689c881a4e6e51cf918d695");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RetrofitRxjavaResult>() {
                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "onCompleted() called");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError() called");
                    }

                    @Override
                    public void onNext(RetrofitRxjavaResult retrofitRxjavaResult) {
                        Log.d(TAG, "onNext:" + retrofitRxjavaResult);
                        if (retrofitRxjavaResult != null) {
                            RetrofitRxjavaResult.ResultBean result = retrofitRxjavaResult.getResult();
                            if (result != null) {
                                List<RetrofitRxjavaResult.ResultBean.DataBean> data = result.getData();
                                MyListViewAdapter adapter = new MyListViewAdapter(RetrofitRxjavaActivity.this, data);
                                listView.setAdapter(adapter);
                            }
                        } else {
                            ToastUtils.showText("服务器数据错误");
                        }
                    }
                });
       }

}

4.ListView的BaseAdapter

package com.example.androidvideo.adpater;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.androidvideo.R;
import com.example.androidvideo.bean.RetrofitRxjavaResult;
import com.example.androidvideo.customView.MyImageView;

import java.util.List;

/**
 * 作者:Android
 * 时间:2018/9/12 17:11
 * 功能:ListView的适配器
 */
public class MyListViewAdapter extends BaseAdapter {
    private final List<RetrofitRxjavaResult.ResultBean.DataBean> data;
    private LayoutInflater mInflater;
    public MyListViewAdapter(Context context, List<RetrofitRxjavaResult.ResultBean.DataBean> data) {
        mInflater = LayoutInflater.from(context);
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int postion, View convertView, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.list_item, null, false); //加载布局
            holder = new ViewHolder();

            holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
            holder.tvDate = (TextView) convertView.findViewById(R.id.tv_date);
            holder.imageView = (MyImageView) convertView.findViewById(R.id.image_view);

            convertView.setTag(holder);
        } else {   //else里面说明,convertView已经被复用了,说明convertView中已经设置过tag了,即holder
            holder = (ViewHolder) convertView.getTag();
        }

        RetrofitRxjavaResult.ResultBean.DataBean bean = data.get(postion);
        holder.tvTitle.setText(bean.getTitle());
        holder.tvDate.setText(bean.getDate());
        holder.imageView.setImageURL(bean.getThumbnail_pic_s());

        return convertView;
    }

    private class ViewHolder {
        MyImageView imageView;
        TextView tvTitle;
        TextView tvDate;
    }
}

整理,作为笔记。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值