Aung P
Aung P

Reputation: 135

Http GET request with parameters in Okhttp Android Kotlin

I am trying to process Http GET request with parameters using Okhttp in Android Kotlin.

As there is no GET resource found on documentation and other internet resources didn't work, how can I set GET request in Okhttp with pre defined parameters.

Builder code with lack of GET method

val parameter  = "{\"phone\": \"$phone\"}"

val request = Request.Builder().url(weburl)
.header("User-Agent", "OkHttp Headers.java")
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
//.method("GET",parameter.toRequestBody())
.build()

Output result enter image description here

Upvotes: 3

Views: 3535

Answers (1)

Mafor
Mafor

Reputation: 10651

If you want to send the phone as a query parameter, you should add it to the request URL, not to the request body. You don't need to specify the method: GET is the default. By the way, you can get rid of the Content-type header (GET requests, usually, have no content):

val url = weburl.toHttpUrl().newBuilder()
    .addQueryParameter("phone", phone)
    .build()

val request = Request.Builder().url(url)
    .header("User-Agent", "OkHttp Headers.java")
    .header("Accept", "application/json")
    .build()

If your requirement is to send a GET request with a request body, than you are out of luck I'm afraid: OkHttp does not support it. Anyways, most likely, it's not what you want (unless you are calling Elasticsearch API...)

Upvotes: 5

Related Questions