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")
相关推荐
fatiaozhang952710 小时前
晶晨线刷工具下载及易错点说明:生成工作流程XML失败
android·xml·网络·电视盒子·刷机固件·机顶盒刷机
CYRUS_STUDIO11 小时前
Frida + FART 联手:解锁更强大的 Android 脱壳新姿势
android·操作系统·逆向
阿华的代码王国12 小时前
【Android】使用Handler做多个线程之间的通信
android·handler·线程通信
DevRen12 小时前
实现Google原生PIN码锁屏密码效果
android·前端·kotlin
雨白12 小时前
自定义 ViewGroup:实现一个流式标签布局
android
没有了遇见13 小时前
免费替代高德 / 百度!Android 原生定位 + GeoNames 离线方案:精准经纬度与模糊位置工具包
android
mucheni13 小时前
迅为RK3588开发板安卓串口RS485App开发-硬件连接
android