Android原生HttpURLConnection上传图片方案

创建上传方法

Kotlin 复制代码
object FormUploader {
    private val BOUNDARY = "Boundary-" + System.currentTimeMillis()
    private const val LINE_FEED = "\r\n"

    @Throws(IOException::class)
    fun uploadImage(url: String, imageFile: File, params: MutableMap<String?, String?>): String {
        val connection = URL(url).openConnection() as HttpURLConnection
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY)
        connection.setDoOutput(true)

        connection.getOutputStream().use { outputStream ->
            DataOutputStream(outputStream).use { writer ->

                // 写入文本参数
                for (entry in params.entries) {
                    writer.writeBytes("--" + BOUNDARY + LINE_FEED)
                    writer.writeBytes("Content-Disposition: form-data; name=\"" + entry.key + "\"" + LINE_FEED)
                    writer.writeBytes(LINE_FEED)
                    writer.writeBytes(entry.value + LINE_FEED)
                }

                // 写入文件数据
                writer.writeBytes("--" + BOUNDARY + LINE_FEED)
                writer.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFile.getName() + "\"" + LINE_FEED)
                writer.writeBytes("Content-Type: image/*" + LINE_FEED)
                writer.writeBytes(LINE_FEED)

                Files.copy(imageFile.toPath(), outputStream)
                writer.writeBytes(LINE_FEED)
                writer.writeBytes("--" + BOUNDARY + "--" + LINE_FEED)
            }
        }
        // 处理响应
        return readResponse(connection)
    }

    @Throws(IOException::class)
    private fun readResponse(connection: HttpURLConnection): String {
        BufferedReader(InputStreamReader(connection.getInputStream())).use { reader ->
            val response = StringBuilder()
            var line: String?
            while ((reader.readLine().also { line = it }) != null) {
                response.append(line)
            }
            return response.toString()
        }
    }

调用上传图片方法

Kotlin 复制代码
 viewModelScope.launch(Dispatchers.IO) {
                    LogUtils.w("开始上传了........................")
                    val map = mutableMapOf<String?, String?>()
                    map.put("appKey", "123456")
                    map.put("token", "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNzg3Mzg0NTA4OSIsImxvZ2luX3VzZXJfa2V5IjoiZjFkMGRkODEtNzg2ZC00YzE1LWE4ZmYtYmQxZWM1Njk2M2I5")
                    map.put("timestamp", "2025-08-26 17:01:15")
                    map.put("ver", "1.0")
                    map.put("sign", "0ecbff7239c7650b75637522683ec7d")
                    val result = FormUploader.uploadImage(
                        "https://127.0.0.1/gatewayApi/sign/common/commonDeal/upload",
                        intent.file,
                        map
                    )
                    LogUtils.w("上传完成结果:$result")
相关推荐
星霜笔记1 天前
GitMob — 手机端 GitHub 管理工具
android·kotlin·github·android jetpack
LiuYaoheng1 天前
问题记录:Android Studio Low memory
android·ide·android studio
独隅1 天前
Python 标准库 (Standard Library) 全面使用指南
android·开发语言·python
always_TT1 天前
strlen、strcpy、strcat等常用字符串函数
android
qqty12171 天前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_895521341 天前
MySQL中between and的基本用法
android·数据库·mysql
云云鬼才1 天前
CoCo编辑器、图形化编程怎么调用Scheme(跳转应用)
android
Jason__Young1 天前
Android ViewModel为什么能够跨越Activity的生命周期?
android
TechMix1 天前
【性能优化】RenderThread各工作阶段梳理
android·性能优化
草莓熊Lotso1 天前
MySQL 内置函数指南:日期、字符串、数学函数实战
android·java·linux·运维·数据库·c++·mysql