Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65884020/http-get-request-with-parameters-in-okhttp-android-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...