HTTP Request in Kotlin

后端 未结 11 2470
不知归路
不知归路 2020-11-28 06:59

I\'m completely new to Kotlin. I want to do a login validation using POST method and to get some information using GET method. I\'ve URL, server Username and Password alread

11条回答
  •  遥遥无期
    2020-11-28 07:19

    I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

    val url = "https://example.com/endpoint"
    
    val client = OkHttpClient()
    
    val JSON = MediaType.get("application/json; charset=utf-8")
    val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
    val request = Request.Builder()
            .addHeader("Authorization", "Bearer $token")
            .url(url)
            .post(body)
            .build()
    
    val  response = client . newCall (request).execute()
    
    println(response.request())
    println(response.body()!!.string())
    

    Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

    UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

    Get Method

    fun get() {
        val client = OkHttpClient()
        val url = URL("https://reqres.in/api/users?page=2")
    
        val request = Request.Builder()
                .url(url)
                .get()
                .build()
    
        val response = client.newCall(request).execute()
    
        val responseBody = response.body!!.string()
    
        //Response
        println("Response Body: " + responseBody)
    
        //we could use jackson if we got a JSON
        val mapperAll = ObjectMapper()
        val objData = mapperAll.readTree(responseBody)
    
        objData.get("data").forEachIndexed { index, jsonNode ->
            println("$index $jsonNode")
        }
    }
    

    POST Method

    fun post() {
        val client = OkHttpClient()
        val url = URL("https://reqres.in/api/users")
    
        //just a string
        var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"
    
        //or using jackson
        val mapperAll = ObjectMapper()
        val jacksonObj = mapperAll.createObjectNode()
        jacksonObj.put("name", "Rolando")
        jacksonObj.put("job", "Fakeador")
        val jacksonString = jacksonObj.toString()
    
        val mediaType = "application/json; charset=utf-8".toMediaType()
        val body = jacksonString.toRequestBody(mediaType)
    
        val request = Request.Builder()
                .url(url)
                .post(body)
                .build()
    
        val response = client.newCall(request).execute()
    
        val responseBody = response.body!!.string()
    
        //Response
        println("Response Body: " + responseBody)
    
        //we could use jackson if we got a JSON
        val objData = mapperAll.readTree(responseBody)
    
        println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
    }
    

提交回复
热议问题