首先添加依赖:
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.android.support:design:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
compile 'com.github.florent37:retrooup:1.0.4'
compile 'com.github.florent37:rxoup:1.0.4'
compile 'org.oup:oup:1.10.2'
compile 'io.reactivex.rxjava2:rxjava:2.1.3'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.just.agentweb:agentweb:2.0.0'
testCompile 'junit:junit:4.12'
annotationProcessor 'com.github.florent37:retrooup-compiler:1.0.4' 封装地址:
public class API {
public static final String BLOG_BASE_URL = "http://www.ruanyifeng.com/blog/archives.html";
}
封装网络请求的类:
package com.shenxuesong.franklog.net;
import com.github.florent37.retrooup.RetroJsoup;
import org.oup.Jsoup;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
public class JsoupHelper {
private static OkHttpClient mOkHttpClient;
static {
initOkHttpClient();
}
/**
* 初始化OKHttpClient,设置缓存,设置超时时间,设置打印日志,设置UA拦截器
*/
private static void initOkHttpClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
if (mOkHttpClient == null) {
synchronized (Jsoup.class) {
if (mOkHttpClient == null) {
mOkHttpClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(30TimeUnit.SECONDS)
.writeTimeout(20TimeUnit.SECONDS)
.readTimeout(20TimeUnit.SECONDS)
.build();
}
}
}
}
private static <T> T createApi(Class<T> clazzString webUrl) {
return new RetroJsoup.Builder()
.url(webUrl)
.client(new OkHttpClient())
.build()
.create(clazz);
}
public static ServiceApi getBlogFeed() {
return createApi(ServiceApi.classAPI.BLOG_BASE_URL);
}
}打开网页查看网页源码!封装bean类
public class ArticleTitle {
@JsoupText("li")
public String title;
@JsoupHref("a")
public String url;
}public interface ServiceApi {
@Select("div#beta-inner li")
Observable<ArticleTitle> getContent();
@Select("div.module-categories li")
Observable<ArticleTitle> getTitle();
}
Observable<ArticleTitle> observable = JsoupHelper.getBlogFeed().getTitle();
observable.toList()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<List<ArticleTitle>>() {
@Override
public void accept(List<ArticleTitle> articleTitles) throws Exception {
successAndFailure.getSuccess(articleTitles);
}
});
本文介绍了如何将现有的Web网站转换成一款可以在手机上使用的应用程序,通过封装技术,实现Web内容在移动设备上的无缝浏览体验。
7197






