Retrofit是Square公司开源的一个基于OkHttp实现的Android网络请求框架,它将我们自己开发的底层的代码和细节都封装了起来。
https://github.com/square/retrofit
http://square.github.io/retrofit/

配置Retrofit

在/app/build.gradle配置中加入

compile 'com.squareup.retrofit2:retrofit:2.3.0'compile 'com.squareup.retrofit2:converter-gson:2.3.0'

最后一行是为了增加支持返回值为JSON类型数据所添加的依赖包,如有需要可自行添加其他包

Gson: com.squareup.retrofit2:converter-gsonJackson: com.squareup.retrofit2:converter-jacksonMoshi: com.squareup.retrofit2:converter-moshiProtobuf: com.squareup.retrofit2:converter-protobufWire: com.squareup.retrofit2:converter-wireSimple XML: com.squareup.retrofit2:converter-simplexmlScalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

网络访问接口

interface IpService {    //GET    @GET("getIpInfo.php?ip=59.108.54.37")    fun getIpMsg():Call    //动态配置URL地址    @GET("{path}/getIpInfo.php?ip=59.108.54.37")    fun getIpMsgPath(@Path("path") path: String):Call    //动态指定查询条件    @GET("getIpInfo.php")    fun getIpMsgQuery(@Query("ip") ip:String):Call    //动态指定查询条件组    @GET("getIpInfo.php")    fun getIpMsgQueryMap(@QueryMap option:Map):Call    //Post 表单形式请求    @FormUrlEncoded    @POST("getIpInfo.php")    fun getIpMsgPost(@Field("ip") first:String):Call    //POST JSON数据请求    @POST("getIpInfo.php")    fun getIpMsgPostBody(@Body ip: Ip):Call    //单文件上传    @Multipart    @POST("user/photo")    fun upDateUser(@Part photo: MultipartBody.Part, @Part("description") description: RequestBody):Call    //多文件上传    @Multipart    @POST("user/photo")    fun upDateUser(@PartMap photos:Map, @Part("description") description: RequestBody):Call    //静态添加消息报头    @GET("some/endpoint")    @Headers("Accept-Encoding:application/json")    fun getCarType():Call    //动态添加消息报头    @GET("some/endpoint")    fun getCarType(@Header("Location") location:String):Call}

创建Retrofit实例

 val retrofit: Retrofit =  Retrofit.Builder()                .baseUrl("http://ip.taobao.com/service/")                .addConverterFactory(GsonConverterFactory.create())                .build()        val ipService = retrofit.create(IpService::class.java)

发起请求

        ipService.getIpMsg().enqueue(object:Callback{            override fun onResponse(call: Call?, response: Response?) {                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.            }            override fun onFailure(call: Call?, t: Throwable?) {                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.            }        })        ipService.getIpMsgQuery("202.204.105.195").enqueue(object :Callback{            override fun onFailure(call: Call?, t: Throwable?) {                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.            }            override fun onResponse(call: Call?, response: Response?) {                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.            }        })

以下是一个具体实例

请求接口

interface ApiService {    @GET("china")    fun getProvince(): Call>;    @GET("china/{params}")    fun getCity(@Path("params") id: String): Call>;}

创建Retrofit实例

val retrofit: Retrofit =  Retrofit.Builder()        .baseUrl("http://guolin.tech/api/")        .addConverterFactory(GsonConverterFactory.create())        .build()val api = retrofit.create(ApiService::class.java)

发起请求

fun province() = api.getProvince()fun getProvince(){    province().enqueue(object : Callback> {        override fun onResponse(call: Call>?, response: Response>?) {            for(i in 0.. response!!.body()!!.size-1){                System.out.println(response!!.body()!!.get(i).name)            }        }        override fun onFailure(call: Call>?, t: Throwable?) {            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.        }    })}

Retrofit简单使用(Kotlin)_第1张图片

更多相关文章

  1. Android 增量更新实例(Smart App Updates)
  2. Android之SimpleAdapter简单实例和SimpleAdapter参数说明(zt)
  3. NDK/JNI02-实例开发流程
  4. 我要一步一步往上爬——Android应用实例笔记(1)—手势
  5. Android ListView 滚动条的设置详解及实例代码
  6. Android开发之动态加载,运行未安装apk
  7. Android中使用Movie显示gif动态图

随机推荐

  1. android 使用广播监听网络状态
  2. 【Android】通过耳机调起语音助手App配置
  3. Android:ImageView 设置图片
  4. android 获得监听某一广播的所有程序
  5. Android手机中紧急号码的定制
  6. Android调用系统分享功能以及createChoos
  7. Android(安卓)Studio 简单功能介绍
  8. Android 动画1--View控件的显示和隐藏效
  9. android设置隐藏软键盘
  10. Android camera调用出现错误解决方法