国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

android 開發中使用okhttp上傳文件到服務器

2019-10-22 18:17:06
字體:
來源:轉載
供稿:網友

開發android手機客戶端,常常會需要上傳文件到服務器,比如:你手機里的照片。

使用okhttp會是一個很好的選擇。它使用很簡單,而且運行效率也很高。

首先,在 app/build.gradle 的 dependencies 增加 implementation 'com.squareup.okhttp3:okhttp:3.8.1' 可以參照如下代碼

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'}

在界面上添加一個按鈕,以及一個可滾動顯示返回值的文字組件。

<Button      android:id="@+id/btnOkHttpUploadFilePost"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_weight="1"      android:text="OkHttp上傳文件(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>

因為只是基本功能實現,所以采用發送手機上指定的一個文件就達成目的。

在代碼編輯區,首先添加一個默認的服務器地址。

//設置訪問服務端IP  var serverIp = "192.168.1.105"

在onCreate方法內添加按鈕操作代碼

//post方式上傳文件(sd卡跟路徑image.png文件)    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()    }

這段代碼中的 val url 值是根據服務端的要求設置的。

val file 是手機上圖片文件的位置。

val requestBody 中 .addFormDataPart("uploadfile", "image.png", fileBody) 的 uploadfile 也是服務端要求的必要鍵。

最后的 responseStr 是上傳操作之后,獲取服務端的信息反饋。

okhttp,上傳文件,android

總結

以上所述是小編給大家介紹的android 開發中使用okhttp上傳文件到服務器,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 嘉善县| 子长县| 开江县| 博客| 南昌市| 临高县| 霍州市| 兴业县| 洛川县| 广汉市| 衡山县| 铅山县| 姜堰市| 新绛县| 土默特右旗| 河津市| 珠海市| 广西| 信宜市| 固原市| 正蓝旗| 远安县| 晴隆县| 红河县| 日土县| 遵义县| 尚义县| 永济市| 姚安县| 大英县| 崇明县| 城固县| 遂昌县| 石林| 华坪县| 辽阳县| 桐城市| 阿尔山市| 安陆市| 邛崃市| 桃源县|