feiyu_073的博客

每天进步一点点

Rejava + retrofit + okhttp 简单操作

第一步,添加依赖

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'io.reactivex.rxjava2:rxjava:2.1.1'

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'//配合Rxjava 使用

第二步,构建 okhttp

public class MyUtils {


    public static OkHttpClient getOkHttpClient(Activity activity) {


        //初始化OkHttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)    //连接   超时时间
                .readTimeout(10, TimeUnit.SECONDS)      //读操作 超时时间
                .writeTimeout(10, TimeUnit.SECONDS)     //写操作 超时时间
.cookieJar(new CookiesManager(this))
.build();
return client; }}

第三步,创建接口


public interface AppURL {


    String url_1 = "top250";

    @GET(url_1)
    Observable<MovieSubject> getMovieObservable(@Query("start") int start, @Query("count") int count);

}




第四步,构建retrofit并请求网络

private void initAll() {

        String movie_url = "https://api.douban.com/v2/movie/";

        OkHttpClient okHttpClient = MyUtils.getOkHttpClient(this);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(movie_url)
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                //要使用retroiftrexjava配合使用这个方法必须有,不然会报Unable to create call adapter
                // for rx.Observable<com.ethanco.retrofit2_0test.HomeTopBean>异常
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)//整合okhttp
                .build();

        final AppURL appURL = retrofit.create(AppURL.class);


        //////////////////////////////////////////////////

        Observable<MovieSubject> movieObservable = appURL.getMovieObservable(0, 20);
        movieObservable.subscribeOn(Schedulers.io())//使请求网络的操作运行在子线程
                .observeOn(AndroidSchedulers.mainThread())//使后面的subscribe运行在主线程
                .subscribe(new Observer<MovieSubject>() {

                    private Disposable mDisposable;

                    @Override
                    public void onSubscribe(Disposable d) {//订阅
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(MovieSubject bean) {
                        List<MovieSubject.SubjectsBean> subjects = bean.getSubjects();
                        if (subjects != null) {
                            for (int i = 0; i < subjects.size(); i++) {
                                Log.d(TAG, "----->onNext " + subjects.get(i).getTitle());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        mDisposable.dispose(); //截断操作
                    }
                });

    }


避免gson解析json时出现空指针:

private Gson getGson() {

    GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(String.class, new StringConverter());

    if (gson == null) {
        gson = gb.create();
    }
    return gson;
}
/**
 * 避免gson解析json时出现空指针
 */
public class StringConverter implements JsonSerializer<String>, JsonDeserializer<String> {

    public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) {
            return new JsonPrimitive("");
        } else {
            return new JsonPrimitive(src.toString());
        }
    }

    public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
            throws JsonParseException {
        return json.getAsJsonPrimitive().getAsString();
    }
}

/**
 * 自动管理Cookies
 */
public class CookiesManager implements CookieJar {

    private String TAG = "==CookiesManager";
    private Context mContext;
    private PersistentCookieStore cookieStore;


    public CookiesManager(Context context) {
        this.mContext = context;
        cookieStore = new PersistentCookieStore(mContext);
    }


    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie item : cookies) {
                cookieStore.add(url, item);
                Log.d(TAG, "saveFromResponse -----> url.host() = " + url.host() + " domain = " + item.domain());
            }
        }
    }

    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        List<Cookie> cookies = cookieStore.get(url);
        Log.d(TAG, "loadForRequest -----> url.host() = " + url.host());
        if (cookies != null) {
            for (int i = 0; i < cookies.size(); i++) {
                String domain = cookies.get(i).domain();
                Log.d(TAG, "-----> loadForRequest  domain = " + domain);
            }
        }
        return cookies;
    }
}

随记,技术有限,不喜勿喷

阅读更多
上一篇判断java字符串是否为数字
下一篇Android 6.0 获取权限拍照
想对作者说点什么? 我来说一句

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

关闭
关闭