Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute raw graphQL query using OkHttp Client

I have a graphQL query that I want to execute it as raw request and don't want to depend on any clients to execute this request (I don't want to use apollo client for android to execute it)

I have created the string that forms this query and tries to make this request using OkHttp client but I think there is something missing because of every time I send the request the respond is internal server error. But if I execute this query using apollo-client for android it returns with a response.

Here is my try for executing the raw query request using OkHttp:

val requestBodyString = "  cities{\n" +
            "    name\n" +
            "  }"

fun makeRequest(url: String): Response{
        val client = OkHttpClient()
        val requestBody = RequestBody.create(null, requestBodyString)
        val request = Request.Builder().url(url).post(requestBody)
            .addHeader("content-type", "application/graphql").build()
        return client.newCall(request).execute()
    }

I follow yelp documentation for making requests but it doesn't work for me. and I can't figure why?

like image 478
Shalan93 Avatar asked Oct 18 '25 01:10

Shalan93


1 Answers

Try to send as a JSON

    val query = "  cities{\n" +
            "    name\n" +
            "  }"

   fun makeRequest(url: String): Response{
            val client = OkHttpClient()

           val json = JSONObject()
           json.put("query",query)

            val requestBody = RequestBody.create(null, json.toString())
            val request = Request.Builder().url(url).post(requestBody)
                .addHeader("content-type", "application/json").build()
            return client.newCall(request).execute()
        }
like image 185
Anderson Soares Avatar answered Oct 20 '25 16:10

Anderson Soares