温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android 开发中使用okhttp上传文件到服务器

发布时间:2020-10-04 08:16:41 来源:脚本之家 阅读:217 作者:厚土火焰山 栏目:移动开发

开发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 是上传操作之后,获取服务端的信息反馈。

android 开发中使用okhttp上传文件到服务器 

总结

以上所述是小编给大家介绍的android 开发中使用okhttp上传文件到服务器,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI