@@ -7,8 +7,10 @@ import kotlinx.serialization.json.Json
77import kotlinx.serialization.Serializable
88import kotlinx.serialization.json.JsonElement
99import java.io.IOException
10+ import java.io.ByteArrayOutputStream
1011import java.net.HttpURLConnection
1112import java.net.URL
13+ import java.util.zip.GZIPOutputStream
1214
1315@Serializable
1416data class GraphQLRequest (
@@ -71,7 +73,8 @@ class GraphQLClient(
7173 suspend fun <T > execute (
7274 queryFileName : String ,
7375 variables : Map <String , JsonElement > = emptyMap(),
74- dataSerializer : KSerializer <T >
76+ dataSerializer : KSerializer <T >,
77+ compress : Boolean = true
7578 ): GraphQLResponse <T > = withContext(DispatcherProviderHolder .current.io) {
7679 var connection: HttpURLConnection ? = null
7780 try {
@@ -83,12 +86,16 @@ class GraphQLClient(
8386
8487 val requestJson = json.encodeToString(request)
8588 val requestBytes = requestJson.toByteArray(Charsets .UTF_8 )
89+ val payloadBytes = if (compress) gzip(requestBytes) else requestBytes
8690 val connectionLocal = connectionProvider.openConnection(endpoint).also { connection = it }
8791
8892 connectionLocal.apply {
8993 requestMethod = " POST"
90- setRequestProperty(" Content-Length" , requestBytes .size.toString())
94+ setRequestProperty(" Content-Length" , payloadBytes .size.toString())
9195 setRequestProperty(" Content-Type" , " application/json" )
96+ if (compress) {
97+ setRequestProperty(" Content-Encoding" , " gzip" )
98+ }
9299
93100 // Add custom headers
94101 headers.forEach { (key, value) ->
@@ -98,12 +105,12 @@ class GraphQLClient(
98105 doOutput = true
99106 connectTimeout = CONNECT_TIMEOUT
100107 readTimeout = READ_TIMEOUT
101- setFixedLengthStreamingMode(requestBytes .size)
108+ setFixedLengthStreamingMode(payloadBytes .size)
102109 }
103110
104111 // Send request
105112 connectionLocal.outputStream.use { outputStream ->
106- outputStream.write(requestBytes )
113+ outputStream.write(payloadBytes )
107114 }
108115
109116 // Read response
@@ -141,4 +148,12 @@ class GraphQLClient(
141148 it.readText()
142149 } ? : throw IllegalStateException (" Could not load GraphQL query file: $queryFilepath " )
143150 }
151+
152+ private fun gzip (data : ByteArray ): ByteArray {
153+ val byteStream = ByteArrayOutputStream ()
154+ GZIPOutputStream (byteStream).use { gzipStream ->
155+ gzipStream.write(data)
156+ }
157+ return byteStream.toByteArray()
158+ }
144159}
0 commit comments