Reputation: 21
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.
Upvotes: 1
Views: 5568
Reputation: 1315
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
}
Upvotes: 0
Reputation: 1048
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
Upvotes: 1