Skip to content

Commit

Permalink
#450 ported OkHttp module to Kotlin and upgraded to OkHttp 4.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
gotev committed Aug 15, 2019
1 parent e2afc19 commit 8df85b7
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 213 deletions.
3 changes: 2 additions & 1 deletion examples/app/demoapp/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
Expand Down
2 changes: 1 addition & 1 deletion uploadservice-okhttp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ dependencies {

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

api 'com.squareup.okhttp3:okhttp:3.14.0'
api 'com.squareup.okhttp3:okhttp:4.0.1'
//api "net.gotev:uploadservice:${version}"
//comment the previous line and uncomment the next line for development (it uses the local lib)
api project(':uploadservice')
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package net.gotev.uploadservice.okhttp

import net.gotev.uploadservice.http.BodyWriter
import okio.BufferedSink
import java.io.IOException

/**
* @author Aleksandar Gotev
*/

class OkHttpBodyWriter(private val sink: BufferedSink) : BodyWriter() {
@Throws(IOException::class)
override fun write(bytes: ByteArray) {
sink.write(bytes)
}

@Throws(IOException::class)
override fun write(bytes: ByteArray, lengthToWriteFromStart: Int) {
sink.write(bytes, 0, lengthToWriteFromStart)
}

@Throws(IOException::class)
override fun flush() {
sink.flush()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package net.gotev.uploadservice.okhttp

import net.gotev.uploadservice.ServerResponse
import net.gotev.uploadservice.http.HttpConnection
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.BufferedSink

/**
* @author Aleksandar Gotev
*/
private fun String.requiresRequestBody() = this == "POST" || this == "PUT" || this == "PATCH" || this == "PROPPATCH" || this == "REPORT"

private fun String.permitsRequestBody() = !(this == "GET" || this == "HEAD")

internal fun body(httpMethod: String, bodyLength: Long, contentType: MediaType?, delegate: HttpConnection.RequestBodyDelegate): RequestBody? {
val method = httpMethod.trim().toUpperCase()

if (!method.permitsRequestBody() && !method.requiresRequestBody()) return null

return object : RequestBody() {
override fun contentLength() = bodyLength

override fun contentType() = contentType

override fun writeTo(sink: BufferedSink) {
OkHttpBodyWriter(sink).apply {
delegate.onBodyReady(this)
flush()
}
}
}
}

private fun Response.headersHashMap() = LinkedHashMap(headers.toMap())

private fun Response.bodyBytes() = body?.bytes() ?: ByteArray(0)

internal fun Response.asServerResponse() = ServerResponse(code, bodyBytes(), headersHashMap())

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package net.gotev.uploadservice.okhttp

import net.gotev.uploadservice.http.HttpConnection
import net.gotev.uploadservice.http.HttpStack
import okhttp3.OkHttpClient
import java.io.IOException

/**
* Implementation of the OkHttp Stack.
* @author Aleksandar Gotev
*/
class OkHttpStack(private val client: OkHttpClient = OkHttpClient()) : HttpStack {
@Throws(IOException::class)
override fun createNewConnection(method: String, url: String): HttpConnection {
return OkHttpStackConnection(client, method, url)
}
}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package net.gotev.uploadservice.okhttp

import net.gotev.uploadservice.Logger
import net.gotev.uploadservice.NameValue
import net.gotev.uploadservice.http.HttpConnection
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
import java.net.URL
import java.util.*

/**
* [HttpConnection] implementation using OkHttpClient.
*
* @author Aleksandar Gotev
*/
class OkHttpStackConnection(private val httpClient: OkHttpClient, private val httpMethod: String, url: String) : HttpConnection {

private val requestBuilder = Request.Builder().url(URL(url))
private var bodyLength = 0L
private var contentType: MediaType? = null
private val uuid = UUID.randomUUID().toString()

init {
Logger.debug(javaClass.simpleName, "creating new OkHttp connection (uuid: $uuid)")
}

@Throws(IOException::class)
override fun setHeaders(requestHeaders: List<NameValue>): HttpConnection {
for (param in requestHeaders) {
if ("content-type" == param.name.trim().toLowerCase())
contentType = param.value.trim().toMediaTypeOrNull()

requestBuilder.header(param.name.trim(), param.value.trim())
}

return this
}

override fun setTotalBodyBytes(totalBodyBytes: Long, isFixedLengthStreamingMode: Boolean): HttpConnection {
// http://stackoverflow.com/questions/33921894/how-do-i-enable-disable-chunked-transfer-encoding-for-a-multi-part-post-that-inc#comment55679982_33921894
bodyLength = if (isFixedLengthStreamingMode) totalBodyBytes else -1

return this
}

private fun request(delegate: HttpConnection.RequestBodyDelegate) =
requestBuilder.method(
method = httpMethod,
body = body(httpMethod, bodyLength, contentType, delegate)
).build()

@Throws(IOException::class)
override fun getResponse(delegate: HttpConnection.RequestBodyDelegate) = httpClient
.newCall(request(delegate))
.execute()
.use { it.asServerResponse() }

// Resources are automatically freed after usage. Log only.
override fun close() {
Logger.debug(javaClass.simpleName, "closing OkHttp connection (uuid: $uuid)")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ interface RequestBodyDelegate {
* Sets the total body bytes.
* @param totalBodyBytes total number of bytes
* @param isFixedLengthStreamingMode true if the fixed length streaming mode must be used. If
* it's false, chunked streaming mode has to be used
* it's false, chunked streaming mode has to be used.
* https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88
* @return instance
*/
HttpConnection setTotalBodyBytes(long totalBodyBytes, boolean isFixedLengthStreamingMode);
Expand Down

0 comments on commit 8df85b7

Please sign in to comment.