(android Development) upload files using okhttp

Keywords: Android OkHttp Mobile Junit

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 =
                    [
                            'src/main/res/layout/menufunction',
                            'src/main/res'
                    ]
        }
    }
}

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.

        <Button
            android:id="@+id/btnOkHttpUploadFilePost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="OkHttp Upload files(POST)"
            android:textAllCaps="false" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/ttviewResponse"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </ScrollView>

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 = "192.168.1.105"

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()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("uploadfile", "image.png", fileBody)
                            .build()
                    val request = Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build()
                    val httpBuilder = OkHttpClient.Builder()
                    val okHttpClient = httpBuilder
                            .connectTimeout(10, java.util.concurrent.TimeUnit.SECONDS)
                            .writeTimeout(15, java.util.concurrent.TimeUnit.SECONDS)
                            .build()
                    val response = okHttpClient.newCall(request).execute()
                    val responseStr = response.body()?.string()
                    runOnUiThread { ttviewResponse.text = responseStr }
                } catch (e: Exception) {

                }
            }.start()
        }

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.

 



Author: thick soil fire smoke
Link: https://www.jianshu.com/p/1bcf2f88d577
Source: Jianshu
The copyright of the brief book belongs to the author. For any reprint, please contact the author for authorization and indicate the source.

Posted by kayess2004 on Sat, 02 Nov 2019 12:23:41 -0700