OkHttp是一个优秀的网络请求框架。通过对OkHttp的封装,可以极大的扩展其性能。
okhttp-utils是一个对OkHttp的封装库,原库由hongyang封装,我在其基础上进行了少许的修改,使其更符合我的项目。
1. 在app项目下的build.gradle下依赖库
compile 'com.zhy:okhttputils:2.6.2'
2. 在application中对okhttp-utils进行配置
// 配置okhttputils val okHttpClient = OkHttpClient.Builder() // .addInterceptor(new LoggerInterceptor("TAG")) .connectTimeout(10000L, TimeUnit.MILLISECONDS) .readTimeout(10000L, TimeUnit.MILLISECONDS) //其他配置 .build() OkHttpUtils.initClient(okHttpClient)
2. 在需要上穿json的地方,使用okhttp-utils,项目中使用的是okhttp的post方式提交json
OkHttpUtils .postString() .url(NetApi.url) .content(json.toString()) .mediaType(MediaType.parse("application/json; charset=utf-8")) .build() .execute(MyStringCallback())
3. 处理MyStringCallback
inner class MyStringCallback : StringCallback() { override fun onBefore(request: Request?, id: Int) { //setTitle("loading..."); } override fun onAfter(id: Int) { //setTitle("Sample-okHttp"); } override fun onError(call: Call, e: Exception, id: Int) { e.printStackTrace() Log.e(GTIntentService.TAG, "数据发送失败了") } override fun onResponse(response: String, id: Int) { Log.e(GTIntentService.TAG, "onResponse:complete") Log.e(GTIntentService.TAG, "数据发送成功了") Log.d(GTIntentService.TAG, "response.code()==$response") } }
如此,可以向服务器提交json的数据。