开发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'

}

在界面上添加一个按钮,以及一个可滚动显示返回值的文字组件。

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" />

android:layout_width="match_parent"

android:layout_height="wrap_content">

android:id="@+id/ttviewResponse"

android:layout_width="match_parent"

android:layout_height="match_parent" />

因为只是基本功能实现,所以采用发送手机上指定的一个文件就达成目的。

在代码编辑区,首先添加一个默认的服务器地址。

//设置访问服务端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项目中使用的服务器上,android 开发中使用okhttp上传文件到服务器相关推荐

  1. Android上传文件至服务器(转)

    本实例实现每隔5秒上传一次,通过服务器端获取手机上传过来的文件信息并做相应处理:采用Android+Struts2技术. 一.Android端实现文件上传 1).新建一个Android项目命名为and ...

  2. android上传文件至服务器(android端+服务器端)

    引言:本来android文件上传的博客在网上挺多的,不过好些都只是有前台android端的上传,并没有后台服务器端的接收.而且自己写的时候也确实遇见了一些之前没注意到的地方,写出来也算是给自己提个醒. ...

  3. android 上传文件到服务器

    1.编写layout.xml <LinearLayout android:layout_width="match_parent"android:layout_height=& ...

  4. android -上传文件到服务器

    android上传文件到服务器       重点:最好是设置好content-type这些参数的配置!     package com.spring.sky.image.upload.network; ...

  5. Eclipse新建Android项目后,出现“The import android.support.v7.app cannot be resolved”

    1>在Eclipse中新建Android项目后,出现"The import android.support.v7.app cannot be resolved" 如下图所示: ...

  6. jsch 移动服务器上文件,jsch上传文件到服务器

    需求就是上传文件到服务器,服务器的存储地址由程序决定然后可以自动创建. 使用第三方:jsch JSch 是SSH2的一个纯Java实现.它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文 ...

  7. sftp上传文件服务器,使用SFTP上传文件到服务器的简单使用

    最近用到SFTP上传文件查找了一些资料后自己做了一点总结,方便以后的查询 /** * 将文件上传到服务器 * * @param filePath * 文件路径 * @param channelSftp ...

  8. 服务器如何接收curl上传文件,linux curl上传文件到服务器

    linux curl上传文件到服务器 内容精选 换一换 为了实现通过NAT Server可使用SSH协议跳转到SAP HANA节点的功能,以及SAP HANA节点和NAT Server互相通过SSH协 ...

  9. xutils上传文件到服务器

    import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterfa ...

最新文章

  1. 微信扫描二维码登入实现,网页端
  2. SQL数据库对象的建立
  3. 生效linux内核,Linux内核
  4. lua加密教程_我们相信加密! 教程
  5. windbg 常用命令~*
  6. 类名作为方法和形参的返回值
  7. mac homebrew chinese mirror
  8. mysql 主备心跳监测配置_mysql主备配置
  9. (1)什么是socket(套接字)
  10. 贪心/思维题 UVA 11292 The Dragon of Loowater
  11. 优化理论09-----线性等式约束问题的投影方法、投影最速下降算法、解决方向查找问题(DFP)、牛顿法的修正在线性等式约束、变度量法
  12. ATT拟854亿美元收购时代华纳 国内运营商坐不住了
  13. [bzoj4945][Noi2017]游戏
  14. MATLAB(6)GUI应用介绍
  15. java通过SMTP发送QQ邮件(参考自龙果学院)
  16. Lync Server 2010下载拓扑报错分析及解决方法分享
  17. 单片机循迹车c语言程序,基于单片机控制的简易自动循迹小车仿真与程序源码...
  18. 在教育孩子上少一点功利心,就会快乐?
  19. flutter Spacer 撑开整个屏幕
  20. obs源码分析【八】:显示器采集

热门文章

  1. 关闭oracle job定时任务,oracle job 定时任务,定时执行
  2. 完全平方公式用c语言表达式,完全平方公式教案
  3. 学术之声 | 专访邵俊教授:区块链用技术保证在链上说话算话
  4. win7添加ftp到计算机,技术编辑帮你win7系统FTP地址添加到资源管理器的收藏夹下的设置步骤...
  5. BI选型之国内外BI产品对比分析
  6. 2021-03-19我的博客
  7. 《左手数据,右手图表》
  8. 解析国内冷链物流的发展现状
  9. Flutter运行报错Automatically assigning platform `iOS` with version `9.0` on target `Runner`...
  10. Mac上使用IE浏览器