62. (android Development) upload files using okhttp

To develop android mobile client, you often need to upload files to the server, such as: photos in your mobile phone.
Using okhttp would be a good choice. It is easy to use and efficient to run.
First, add implementation 'com. Square up. Okhttp3: okhttp: 3.8.1' in the dependencies of app/build.gradle. You can refer to the following code

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.cofox.mykt.myweather"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    sourceSets {
        main {
            res.srcDirs =

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation 'org.jetbrains.anko:anko-sdk19:0.10.3'
    implementation 'org.jetbrains.anko:anko-support-v4:0.10.3'
    implementation 'org.jetbrains.anko:anko-appcompat-v7:0.10.3'
    implementation 'com.google.code.gson:gson:2.7'
    implementation 'com.android.support:percent:26.1.0'
    implementation 'com.squareup.okhttp3:okhttp:3.8.1'

Add a button on the interface and a text component that can scroll to display the return value.

            android:text="OkHttp Upload file(POST)"
            android:textAllCaps="false" />
            android:layout_height="match_parent" />

Because it is only a basic function, it can achieve the purpose by sending a specified file on the mobile phone.
In the code editing area, first add a default server address.

    //Set access server IP
    var serverIp = ""

Add button action code in onCreate method

        //Upload file in post mode (sd card and path image.png file)
        btnOkHttpUploadFilePost.setOnClickListener {
            Thread {
                try {
                    val url = "http://" + serverIp + "/upload"
                    val file = File("/sdcard/image.png")
                    val fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file)
                    val requestBody = MultipartBody.Builder()
                            .addFormDataPart("uploadfile", "image.png", fileBody)
                    val request = Request.Builder()
                    val httpBuilder = OkHttpClient.Builder()
                    val okHttpClient = httpBuilder
                            .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                            .writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                    val response = okHttpClient.newCall(request).execute()
                    val responseStr = response.body()?.string()
                    runOnUiThread { ttviewResponse.text = responseStr }
                } catch (e: Exception) {


The val url value in this code is set according to the requirements of the server.
val file is the location of the picture file on the phone.
The uploadfile of. addFormDataPart("uploadfile", "image.png", fileBody) in val requestBody is also the necessary key required by the server.
The last responseStr is to get the information feedback from the server after the upload operation.

Upload renderings

Tags: Android OkHttp Mobile Junit

Posted on Thu, 30 Apr 2020 09:25:31 -0700 by danbot26