使用例子:
val url = "https://www.baidu.com"
NetUtils.getHttp(url, null, object : NewCallBack<String> {
override fun onFail(err: String) {
Log.e("onFail", err)
}
override fun onSuccess(t: String) {
Log.e("onSuccess", t.toString())
}
})
使用范围:联网请求 返回结果 String , Bitmap , 自定义类型
实现1:引入OKhttp的依赖库(这里的例子是Android Studio 3.0 Beta2的引入)
在APP层的build.gradle文件中,dependencies标签下添加一行
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
实现2:编写NewCallBack接口用于请求结果的回调
/**
* Created by 俊华 on 17/8/12.
*/
interface NewCallBack<T> {
/**
* 失败的回调
*/
fun onFail(err: String)
/**
* 成功的回调
*/
fun onSuccess(t: T)
/**
* 获取接口传入的类型<T>
*/
fun Type(): Class<T>? {
val interfacesTypes = this.javaClass.genericInterfaces.get(0) as ParameterizedType
return interfacesTypes.actualTypeArguments[0] as Class<T>
}
}
实现3:编写NetUtils类,用于处理联网请求的逻辑处理
这里我使用到了阿里的fastjson解析,所以要引入依赖库
在(实现1)的下面再添加一行
implementation 'com.alibaba:fastjson:1.2.36'
然后再继续NetUtils的封装
/**
* Created by 俊华 on 17/8/12.
*/
object NetUtils {
private var client: OkHttpClient
private var mHandler: Handler
private var threadPool: Executor
private lateinit var newCallBack: NewCallBack<Any>
private lateinit var url: String
private var params: Map<String, String>? = null
private lateinit var request: Request
init {
client = OkHttpClient()
mHandler = Handler(Looper.getMainLooper())
threadPool = Executors.newCachedThreadPool()
}
/**
* get请求
*/
fun <T> getHttp(url: String?, params: Map<String, String>?, callBack: NewCallBack<T>) {
http(url, params, false, callBack)
}
/**
* post请求
*/
fun <T> postHttp(url: String?, params: Map<String, String>?, callBack: NewCallBack<T>) {
http(url, params, true, callBack)
}
private fun <T> http(url: String?, params: Map<String, String>?, isPost: Boolean, callBack: NewCallBack<T>) {
if (TextUtils.isEmpty(url)) {
Log.e("url", "你输入的路径为空")
} else {
this.url = url as String
this.params = params
this.newCallBack = callBack as NewCallBack<Any>
setRequest(isPost)
runOnNet()
}
}
/**
* 处理自定义的类
*/
fun <T> parseJsonWithFast(jsonData: String, type: Class<T>?): T? {
if (TextUtils.isEmpty(jsonData)) {
return null
}
try {
Log.e("数据类型为自定义", "parseJsonWithFast()")
return JSONObject.parseObject(jsonData, type)
} catch (e: Exception) {
Log.e("fastJson解析数据异常", e.toString())
return null
}
}
private fun setRequest(isPost: Boolean) {
if (params != null) {
if (isPost) {
val requestBody = MultipartBody.Builder()
requestBody.setType(MultipartBody.FORM)
val iterator = params!!.entries.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
requestBody.addFormDataPart(entry.key, entry.value)
}
request = Request.Builder().url(url).post(requestBody.build()).build()
} else {
val urlStr = url + "?" + MapParamToString(params!!)
request = Request.Builder().url(urlStr).build()
}
} else {
request = Request.Builder().url(url).build()
}
}
/**
*处理传入的请求参数
*/
private fun MapParamToString(params: Map<String, String>): String {
if (params != null) {
val stringBuilder = StringBuilder()
val iterator = params.entries.iterator()
while (iterator.hasNext()) {
val entry = iterator.next()
stringBuilder.append(entry.key + "=" + entry.value + "&")
}
val str = stringBuilder.toString().substring(0, stringBuilder.length - 1)
return str
}
return ""
}
private fun runOnNet() {
threadPool.execute {
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
mHandler.post {
newCallBack.onFail("请求失败")
}
}
override fun onResponse(call: Call?, response: Response?) {
if (response != null) {
if (response.isSuccessful) {
when (newCallBack.Type()!!.simpleName) {
"String" -> dealString(response.body()!!.string())
//将响应数据转化为输入流数据
"Bitmap" -> dealBitmip(response.body()!!.byteStream())
else -> dealClazz(response.body()!!.string())
}
} else {
onError("请求失败")
}
} else {
onError("解析错误")
}
}
})
}
}
/**
* 处理图片
*/
private fun dealBitmip(inputStream: InputStream) {
//将输入流数据转化为Bitmap位图数据
val bitmap = BitmapFactory.decodeStream(inputStream)
if (bitmap != null) {
mHandler.post({
newCallBack.onSuccess(bitmap)
})
} else {
onError("转换图片失败")
}
}
/**
* 返回字符串
*/
private fun dealString(res: String?) {
if (res != null) {
if (!TextUtils.isEmpty(res)) {
mHandler.post({
newCallBack.onSuccess(res)
})
} else {
onError("解析错误")
}
} else {
onError("解析错误")
}
}
/**
* 返回错误提示
*/
private fun onError(err: String) {
mHandler.post({
newCallBack.onFail(err)
})
}
/**
* 处理自定义类型
*/
private fun dealClazz(res: String) {
val any = parseJsonWithFast(res, newCallBack.Type())
if (any != null) {
mHandler.post {
newCallBack.onSuccess(any)
}
} else {
onError("解析失败")
}
}
}
以上就是我要分享的用kotlin封装的通用网络引擎内容,如有不当,恳请批评指正
备注:要求比较高的建议使用大神的三方框架,或自行封装,我的这个封 装思路适用 初级程序员或者小白