OkHttp 应该是时下最火热的Http
框架,特别是在Android
开发中用于取代传统的HttpUrlConnection
,极大的提高了开发效率。其用法相对HttpUrlConnection
来说比较简单,但还是传统Java
式的一板一眼,比如一个异步的Post
请求:
OkHttpClient okHttpClient = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("search", "Hello world")
.build();
Request request = new Request.Builder()
.url("https://xxxxx")
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: " + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
Headers headers = response.headers();
for (int i = 0; i < headers.size(); i++) {
Log.d(TAG, headers.name(i) + ":" + headers.value(i));
}
Log.d(TAG, "onResponse: " + response.body().string());
}
});
代码还是比较多的,只要是处理回调的样板代码太多。
想到Kotlin
支持DSL
,用于处理Http
请求这种特定的场景,可以极大的简化代码,增强可读性。于是试着用Kotlin
做了一个DSL
版本的封装,源码在这里okhttp4k。
通过Gradle
添加依赖,就可以在项目中使用了:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
compile 'com.github.enzowyf:okhttp4k:0.2.0'
}
发起一个异步的Get
请求:
Http.get<Weather> {
//tag { MainActivity::class.java }
url { "http://http://api.openweathermap.org/data/2.5/weather" }
params {
"appid" to "xxxxxx"
"q" to "London"
}
//是否异步,默认false
async { true }
converter { GsonConverter(Weather::class.java) }
//指定异步时回调所在的线程
observeHandler { Handler(Looper.getMainLooper()) }
onSuccess { weather ->
text_view.text = weather.name
}
onFailure { e ->
Log.e("wyf", e.localizedMessage ?: e.javaClass.name, e)
text_view.text = e.localizedMessage ?: e.javaClass.name
}
}
结构非常清晰,也没有多余的样板代码,完美!