1

I found a youtube video on how to do a get url but I need to do a post to a REST api. I am unsure on how to do so.

Ive tried to look around on here but most of it is java.

fun fetchJson() {
    println ("attempting to fetch JSON")

    val url = "https://utgapi.shift4test.com/api/rest/v1/transactions/sale"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback {
        override fun onResponse(call: Call?, response: Response?) {
            val body = response?.body()?.string()
            println(body)
            println("try and get json api working there was an error")
        }

        override fun onFailure(call: Call, e: IOException) {
            println("failed to execute request")
}

with the GET i just receive a error because i am not doing a POST request.

Dawhn
  • 21
  • 1
  • 5

2 Answers2

1

Found something here https://stackoverflow.com/a/29795501/5182150 Converting it to kotlin would be like

private val client = OkHttpClient();

 fun run() throws Exception {
val formBody = FormEncodingBuilder()
    .add("search", "Jurassic Park")
    .build() as RequestBody;
val request = new Request.Builder()
    .url("https://en.wikipedia.org/w/index.php")
    .post(formBody)
    .build();

val response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

This should be the gist. You can deal with nullable issues as the studio gives you warnings. Another tip is You can use Retrofit too which works using OkHTTP for network calls. You can find more about retrofit here https://square.github.io/retrofit/ and a good tutorial here https://medium.com/@prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23

Jude Osbert K
  • 940
  • 9
  • 22
  • and if i were to just paste a json where it says .add would it just send the Json? – Dawhn Jun 24 '19 at 17:06
  • https://stackoverflow.com/q/32196424/5182150 Check this link for the header part, and for the json part, You have to add jt as key value pair, calling add(key, value). I think you would be better off using retrofit which provides a better abstraction – Jude Osbert K Jun 24 '19 at 17:15
0

If you are using OkHttp you can check to this code

fun POST(url: String, parameters: HashMap<String, String>, callback: Callback): Call {
    val builder = FormBody.Builder()
    val it = parameters.entries.iterator()
    while (it.hasNext()) {
        val pair = it.next() as Map.Entry<*, *>
        builder.add(pair.key.toString(), pair.value.toString())
    }

    val formBody = builder.build()
    val request = Request.Builder()
            .url(url)
            .post(formBody)
            .build()


    val call = client.newCall(request)
    call.enqueue(callback)
    return call
}
Enzo Lizama
  • 1,214
  • 1
  • 14
  • 23