为 Android Studio 或者 Android 项目设置代理

如果移动端访问不佳,请使用 ==> Github Pages 版。

本文记录给 Android Studio 设置代理,并添加白名单。适用于 Jenkins 等 CI/CD 环境。有修改配置文件和命令行2种方式。

前置环境:一个 HTTP 代理

  • Host:xx.xx.xx.xx
  • Port:xxxx
  • User:userid
  • Password:password

需要加入白名单的域名:*.nonproxydomains.com

配置

有2种使用方式:

  1. 添加代理配置到当前项目或者全局环境下的 gradle.properties
  2. 命令行方式

方式一:修改gradle.properties

如果只想修改当前项目,则修改对象是当前项目下的 gradle.properties 文件

如果想修改后对所有使用 gradle 构建的项目都起作用,则修改当前用户下 .gradle/gradle.properties 文件。对于 类Unix系统(Linux、macOs) 是 ~/.gradle/ 目录(GRADLE_USER_HOME),Windows 是 系统盘下的 /User/XXX/.gradle/ 目录。

要添加的内容如下:

systemProp.http.proxyHost=xx.xx.xx.xx
systemProp.http.proxyPort=xxxx
systemProp.http.proxyUser=userid
systemProp.http.proxyPassword=password
systemProp.http.nonProxyHosts=*.nonproxydomains.com|localhost

systemProp.https.proxyHost=xx.xx.xx.xx
systemProp.https.proxyPort=xxxx
systemProp.https.proxyUser=userid
systemProp.https.proxyPassword=password
systemProp.https.nonProxyHosts=*.nonproxydomains.com|localhost

方式二:命令行方式

首先看个 Android 打包的完整命令,然后根据平台差异做一下说明(以macOS下为例):

cd projectRoot
./gradlew :app:assembleDebug -Dhttp.proxyHost=xx.xx.xx.xx -Dhttp.proxyPort=xxxx -Dhttp.nonProxyHosts=*.nonproxydomains.com|localhost -Dhttp.proxyUser=userid -Dhttp.proxyPassword=password -Dhttps.proxyHost=xx.xx.xx.xx -Dhttps.proxyPort=xxxx -Dhttps.nonProxyHosts=*.nonproxydomains.com|localhost -Dhttps.proxyUser=userid -Dhttps.proxyPassword=password
## 换行看下参数,和配置文件的参数对应
# -Dhttp.proxyHost=xx.xx.xx.xx 
# -Dhttp.proxyPort=xxxx 
# -Dhttp.nonProxyHosts=*.nonproxydomains.com|localhost 
# -Dhttp.proxyUser=userid 
# -Dhttp.proxyPassword=password

# -Dhttps.proxyHost=xx.xx.xx.xx 
# -Dhttps.proxyPort=xxxx 
# -Dhttps.nonProxyHosts=*.nonproxydomains.com|localhost 
# -Dhttps.proxyUser=userid 
# -Dhttps.proxyPassword=password

这里特别说下 http.nonProxyHosts=*.nonproxydomains.com|localhost 中的 | 符号,命令行使用时可能因为平台差异、字符转义问题需要特殊处理。

当然,如果按照上面的方式没有问题,则不需要特殊处理。

对于 Unix/Linux 系统:管道字符 | 可能需要反斜杠 \ 来转义,使它不被解释为 shell 管道。

-Dhttp.nonProxyHosts=*.nonproxydomains.com|localhost
# 当上面的使用方式有问题时改为:
-Dhttp.nonProxyHosts=*.nonproxydomains.com\|localhost

对于 Windows 系统: | 可能需要反斜杠 ^ 来转。

-Dhttp.nonProxyHosts=*.nonproxydomains.com|localhost
# 当上面的使用方式有问题时改为:
-Dhttp.nonProxyHosts=*.nonproxydomains.com^|localhost

对于使用字符串(双引号包裹)时,也需要转义处理

-Dhttp.nonProxyHosts=*.nonproxydomains|localhost
# 作为字符串处理时
-Dhttp.nonProxyHosts="*.nonproxydomains\|localhost"

如果有什么问题或者意见,可以通过下面的方式和我联系

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,942评论 0 5
  • 前言 这三个知识点不难,但经常用到,如果不看官方文档,有时候并不知道怎么使用,出现问题也不知道原因,所以有必要做一...
    十思叶阅读 13,719评论 2 6
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 11,120评论 0 10
  • https://www.jianshu.com/p/7c288a17cda8 总的来说,Android的系统体系结...
    燕京博士阅读 4,948评论 0 6
  • 嗯 这也许不是第一次了。 到今天好像下雨,大家来的都比较晚,我的门卡放公司了,所以我现在坐在楼下星巴克喝浓郁摩卡。...
    mmmmmming阅读 897评论 1 1