You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin中Volley库如何处理含多个点的URL?

解决Volley解析多级子域名URL的问题

以下是几个可行的解决方法:

  • 用Uri.parse()确保URL格式正确
    不要直接传递字符串URL,通过Android的Uri.parse()方法解析后再使用,避免隐性的格式问题:

    val targetUrl = Uri.parse("https://xxxx.yyyy.net/mobile").toString()
    // 将targetUrl传入Volley请求
    
  • 替换Volley默认的HttpStack为OkHttp
    Volley默认的HttpURLConnection在处理多级子域名时可能存在解析bug,改用OkHttp作为请求栈可以解决该问题:

    1. 先在项目的build.gradle中添加OkHttp依赖:
      implementation("com.squareup.okhttp3:okhttp:4.12.0")
      
    2. 自定义OkHttp实现Volley的HttpStack接口:
      class OkHttpStack(private val client: OkHttpClient) : HttpStack {
          override fun performRequest(request: Request<*>?, additionalHeaders: MutableMap<String, String>?): HttpResponse {
              val url = URL(request?.url)
              val okRequest = Request.Builder().url(url).apply {
                  additionalHeaders?.forEach { (key, value) -> addHeader(key, value) }
                  when (request?.method) {
                      Request.Method.GET -> get()
                      Request.Method.POST -> post(RequestBody.create(null, request.body ?: ByteArray(0)))
                      Request.Method.PUT -> put(RequestBody.create(null, request.body ?: ByteArray(0)))
                      Request.Method.DELETE -> delete()
                      else -> method(request?.method?.toString() ?: "", null)
                  }
              }.build()
      
              val okResponse = client.newCall(okRequest).execute()
              val statusCode = okResponse.code
              val headers = okResponse.headers.toMultimap().mapValues { it.value.firstOrNull() ?: "" }
              val responseBody = okResponse.body?.bytes() ?: ByteArray(0)
      
              return HttpResponse(statusCode, headers, responseBody.size, ByteArrayInputStream(responseBody))
          }
      }
      
    3. 创建Volley的RequestQueue时使用自定义的HttpStack:
      val okHttpClient = OkHttpClient()
      val requestQueue = Volley.newRequestQueue(applicationContext, OkHttpStack(okHttpClient))
      
  • 清除Volley缓存排除旧解析干扰
    若之前的错误域名解析被Volley缓存,可清除缓存后重试:

    requestQueue.cache.clear()
    

内容的提问来源于stack exchange,提问作者Patrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:45:14