我需要从特定网址获取内容类型。我知道我们可以通过简单编码来实现:
URL url = new URL("https://someurl.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD"); // Request Method: GET/POST/UPDATE...
connection.connect();
String contentType = connection.getContentType();
由于这会阻止UI线程(同步操作),如何在Android上使用RxJava 2发出HTTP请求?
注意:
答案 0 :(得分:0)
使用RxJava just运算符离开主线程并继续计算调度程序的线程进程,然后使用flatMap进行http调用并查找内容类型,网络调用应该在IO调度程序的线程上运行,最后在主线程和订阅上观察结果。
Observable.just(1).subscribeOn(Schedulers.computation())
.flatMap(dummyValueOne -> {
return Observable.just(getContentType).subscribeOn(Schedulers.io());
}).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
@Override
public void accept(String contentType) throws Exception {
//do nextsteps with contentType, you can even update UI here as it runs on main thread
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.e("GetContentType", "exception getting contentType", throwable);
}
}));