Kotlin基礎(9)——Kotlin中使用Retrofit發送網絡請求

(1)引入Retrofit庫

// network
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

(2)寫一個接口類

interface GitHubApi {
    
    @GET("/users/{owner}")
    fun getRepository(@Path("owner") owner:String) : Call<RepositoryBean>

}

其中接口類中用到了一個Bean類:RepositoryBean

這裏用到了一個插件,我們知道在Java中,可以通過GsonFormat插件,把Json一鍵生成對應的Bean。而在Kotlin中我們也使用到了這樣一個插件:JsonToKotlinClass,快捷鍵是Alt+K

我們以訪問接口:https://api.github.com/users/xinyitiandi 爲例:

{
  "login": "xinyitiandi",
  "id": 11599121,
  "node_id": "MDQ6VXNlcjExNTk5MTIx",
  "avatar_url": "https://avatars0.githubusercontent.com/u/11599121?v=4",
  "gravatar_id": "",
  "url": "https://api.github.com/users/xinyitiandi",
  "html_url": "https://github.com/xinyitiandi",
  "followers_url": "https://api.github.com/users/xinyitiandi/followers",
  "following_url": "https://api.github.com/users/xinyitiandi/following{/other_user}",
  "gists_url": "https://api.github.com/users/xinyitiandi/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/xinyitiandi/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/xinyitiandi/subscriptions",
  "organizations_url": "https://api.github.com/users/xinyitiandi/orgs",
  "repos_url": "https://api.github.com/users/xinyitiandi/repos",
  "events_url": "https://api.github.com/users/xinyitiandi/events{/privacy}",
  "received_events_url": "https://api.github.com/users/xinyitiandi/received_events",
  "type": "User",
  "site_admin": false,
  "name": null,
  "company": null,
  "blog": "",
  "location": null,
  "email": null,
  "hireable": null,
  "bio": null,
  "public_repos": 12,
  "public_gists": 0,
  "followers": 0,
  "following": 0,
  "created_at": "2015-03-22T15:51:50Z",
  "updated_at": "2020-02-09T07:23:55Z"
}

把Json數據粘貼到裏面:

 生成 RepositoryBean,如下:

data class RepositoryBean(
    val avatar_url: String,
    val bio: Any,
    val blog: String,
    val company: Any,
    val created_at: String,
    val email: Any,
    val events_url: String,
    val followers: Int,
    val followers_url: String,
    val following: Int,
    val following_url: String,
    val gists_url: String,
    val gravatar_id: String,
    val hireable: Any,
    val html_url: String,
    val id: Int,
    val location: Any,
    val login: String,
    val name: Any,
    val node_id: String,
    val organizations_url: String,
    val public_gists: Int,
    val public_repos: Int,
    val received_events_url: String,
    val repos_url: String,
    val site_admin: Boolean,
    val starred_url: String,
    val subscriptions_url: String,
    val type: String,
    val updated_at: String,
    val url: String
)

(3)通過Retrofit來請求接口

fun getRepository(){
        val gitHubApi=Retrofit.Builder().baseUrl("https://api.github.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(GitHubApi::class.java)

        val response=gitHubApi.getRepository("xinyitiandi").execute();
        val repositoryBean=response.body();
        if(repositoryBean!=null){
            runOnUiThread {
                Toast.makeText(this,"請求成功==="+response.message()+"======"+repositoryBean.login,Toast.LENGTH_LONG).show()
                Log.e("======",repositoryBean.login+"   請求成功==="+response.message()+"===="+response.errorBody())
            }

        }else{

            runOnUiThread {
                Toast.makeText(this,"訪問出錯了===",Toast.LENGTH_LONG).show()
                Log.e("====","訪問出錯了")
            }

        }
}

(4)調用方法(注意,這裏沒有用到R小Java,所以另起一個線程請求接口,而請求到結果以後,通過Toast彈出消息,也要在主線程中彈出)

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        thread (){
            getRepository()
        }


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章