Retrofit简单使用(Kotlin)

本文介绍了如何在Android应用中使用Retrofit进行网络请求。首先,讲解了在build.gradle中配置Retrofit及其依赖。接着,阐述了定义网络接口和创建Retrofit实例的步骤。最后,展示了发起HTTP请求的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

网络访问接口

interface IpService {

    //GET
    @GET("getIpInfo.php?ip=59.108.54.37")
    fun getIpMsg():Call<IpModel>

    //动态配置URL地址
    @GET("{path}/getIpInfo.php?ip=59.108.54.37")
    fun getIpMsgPath(@Path("path") path: String):Call<IpModel>

    //动态指定查询条件
    @GET("getIpInfo.php")
    fun getIpMsgQuery(@Query("ip") ip:String):Call<IpModel>

    //动态指定查询条件组
    @GET("getIpInfo.php")
    fun getIpMsgQueryMap(@QueryMap option:Map<String,String>):Call<IpModel>

    //Post 表单形式请求
    @FormUrlEncoded
    @POST("getIpInfo.php")
    fun getIpMsgPost(@Field("ip") first:String):Call<IpModel>

    //POST JSON数据请求
    @POST("getIpInfo.php")
    fun getIpMsgPostBody(@Body ip: Ip):Call<IpModel>

    //单文件上传
    @Multipart
    @POST("user/photo")
    fun upDateUser(@Part photo: MultipartBody.Part, @Part("description") description: RequestBody):Call<User>
    //多文件上传
    @Multipart
    @POST("user/photo")
    fun upDateUser(@PartMap photos:Map<String,String>, @Part("description") description: RequestBody):Call<User>

    //静态添加消息报头
    @GET("some/endpoint")
    @Headers("Accept-Encoding:application/json")
    fun getCarType():Call<ResponseBody>

    //动态添加消息报头
    @GET("some/endpoint")
    fun getCarType(@Header("Location") location:String):Call<ResponseBody>
}

创建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<IpModel>{
            override fun onResponse(call: Call<IpModel>?, response: Response<IpModel>?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onFailure(call: Call<IpModel>?, 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<IpModel>{
            override fun onFailure(call: Call<IpModel>?, t: Throwable?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onResponse(call: Call<IpModel>?, response: Response<IpModel>?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }
        })

以下是一个具体实例

请求接口

interface ApiService {
    @GET("china")
    fun getProvince(): Call<List<Province>>;

    @GET("china/{params}")
    fun getCity(@Path("params") id: String): Call<List<City>>;
}

创建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<List<Province>> {
        override fun onResponse(call: Call<List<Province>>?, response: Response<List<Province>>?) {

            for(i in 0.. response!!.body()!!.size-1){
                System.out.println(response!!.body()!!.get(i).name)
            }

        }

        override fun onFailure(call: Call<List<Province>>?, t: Throwable?) {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

    })
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值