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

Android Studio 3.1.2中Retrofit 2.4.0依赖无法解析问题求助

解决Retrofit 2.4.0依赖无法解析的问题

Hey there, welcome back to Android development! Let's work through this dependency resolution issue you're facing with Retrofit 2.4.0.

问题回顾

你在Android Studio 3.1.2中创建默认项目(Gradle插件3.1.2),添加Retrofit 2.4.0依赖后,同步时出现了多环境下的依赖解析失败错误:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.squareup.retrofit2:retrofit:2.4.0. Open File Show Details
Unable to resolve dependency for ':app@debugAndroidTest/compileClasspath': Could not resolve com.squareup.retrofit2:retrofit:2.4.0. Open File Show Details
Unable to resolve dependency for ':app@debugUnitTest/compileClasspath': Could not resolve com.squareup.retrofit2:retrofit:2.4.0. Open File Show Details
Unable to resolve dependency for ':app@release/compileClasspath': Could not resolve com.squareup.retrofit2:retrofit:2.4.0. Open File Show Details
Unable to resolve dependency for ':app@releaseUnitTest/compileClasspath': Could not resolve com.squareup.retrofit2:retrofit:2.4.0. Open File Show Details

可能的原因

虽然你的项目和模块build.gradle都配置了google()和jcenter()仓库,但结合Android Studio 3.1.2的版本特性,问题大概率出在:

  1. 旧版本Gradle对google()仓库 shorthand 的解析存在兼容性问题
  2. 网络连接/代理设置导致无法访问jcenter仓库
  3. 本地Gradle缓存损坏

分步解决方案

1. 替换google()为完整Maven仓库URL

Android Studio 3.1.x版本的google()简写可能无法稳定指向Google Maven仓库,我们将其替换为完整URL:

修改后的项目级build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

2. 检查网络与代理设置

  • 确保网络连接稳定,如果处于企业代理环境,需要在Android Studio中配置正确的代理:File > Settings > Appearance & Behavior > System Settings > HTTP Proxy
  • 关闭Gradle离线模式:File > Settings > Build, Execution, Deployment > Build Tools > Gradle,取消勾选"Offline work"

3. 清除Gradle缓存

缓存损坏会导致依赖解析异常,按以下步骤清理:

  1. 关闭Android Studio
  2. 删除项目目录下的.gradle文件夹
  3. 删除全局Gradle缓存目录:
    • macOS/Linux:~/.gradle/caches
    • Windows:C:\Users\<你的用户名>\.gradle\caches
  4. 重新打开Android Studio并执行Gradle同步

4. 尝试兼容的Retrofit版本

如果以上步骤无效,可以尝试切换到与当前环境更兼容的Retrofit版本,比如2.5.0(依然适配你的SDK版本),修改app级build.gradle的依赖行:

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

额外提示

既然你时隔6个月回归开发,后续可以考虑升级到更稳定的Android Studio版本(比如Arctic Fox及以上),新版本在依赖解析、性能和兼容性上都有明显提升。不过按上面的步骤,应该能解决当前3.1.2版本下的问题。

内容的提问来源于stack exchange,提问作者Halil Ibrahim Ozercan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:51:01