Gradle项目中使用HttpUrlBuilder构建URL时遇问题求助
分析你的URL构建函数及潜在问题
首先我先把你的代码和依赖配置整理清楚,再结合OkHttp 3.10.0的特性,梳理几个可能遇到的常见问题及解决办法:
你的URL构建函数
public String buildURL(Departments department) { URL url = new HttpUrl.Builder() .scheme("http") .host("localhost") .port(Integer.valueOf(department.getPort())) .addPathSegments(department.getName()+"/synchronization") .build().url(); return url.toString(); }
你的Gradle依赖配置
compile group: 'com.squareup.okio', name: 'okio', version: '1.0.0' compile 'com.squareup.okhttp3:okhttp:3.10.0'
1. 端口转换的空指针/格式异常问题
如果department.getPort()返回null或者非数字字符串,Integer.valueOf()会直接抛出NullPointerException或NumberFormatException。建议先做参数合法性校验:
public String buildURL(Departments department) { // 先校验核心参数非空 if (department == null || department.getPort() == null || department.getName() == null) { throw new IllegalArgumentException("Department、port或name不能为null"); } int port; try { port = Integer.parseInt(department.getPort()); } catch (NumberFormatException e) { throw new IllegalArgumentException("端口格式错误:" + department.getPort(), e); } URL url = new HttpUrl.Builder() .scheme("http") .host("localhost") .port(port) .addPathSegments(department.getName() + "/synchronization") .build().url(); return url.toString(); }
2. 路径的URL编码问题
addPathSegments会自动处理斜杠,但如果department.getName()包含空格、中文或特殊字符,会导致URL不符合规范。建议对名称做URL编码:
import java.net.URLEncoder; import java.nio.charset.StandardCharsets; // ... String encodedName = URLEncoder.encode(department.getName(), StandardCharsets.UTF_8.name()); URL url = new HttpUrl.Builder() .scheme("http") .host("localhost") .port(port) .addPathSegments(encodedName + "/synchronization") .build().url();
3. OkHttp与OkIo版本兼容性问题
OkHttp 3.10.0对应的兼容OkIo版本是1.14.0,你当前用的1.0.0版本太旧,可能引发运行时依赖冲突。建议更新OkIo依赖:
compile group: 'com.squareup.okio', name: 'okio', version: '1.14.0' compile 'com.squareup.okhttp3:okhttp:3.10.0'
4. 端口范围合法性问题
如果端口值超出0-65535的合法范围,HttpUrl.Builder.build()会抛出IllegalArgumentException,建议提前校验:
if (port < 0 || port > 65535) { throw new IllegalArgumentException("端口必须在0-65535之间:" + port); }
内容的提问来源于stack exchange,提问作者maciejka
相关产品推荐
相关产品推荐

