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

Retrofit连接问题:配置正确却无法连接到端点

解决Retrofit无法连接Render端点的问题

以下是排查和解决该连接问题的关键步骤:

1. 先验证API端点可用性

用curl或Postman直接调用端点,确认服务本身是否正常:

curl -X POST https://rainfallpredictionmodel.onrender.com/predict/rainfall \
  -H "Content-Type: application/json" \
  -d '{"state":"KERALA","year":"1901"}'

Render免费实例会休眠,首次请求需约30秒唤醒,若测试能正常返回数据,说明服务无问题,问题出在Android端配置或网络环境。

2. 检查Android网络权限

确保AndroidManifest.xml中已添加互联网权限:

<uses-permission android:name="android.permission.INTERNET" />

缺少该权限会导致所有网络请求直接失败。

3. 适配Android 9+网络安全策略

Android 9及以上默认限制非安全网络请求,即便使用HTTPS,若遇到域名或证书验证问题,需配置网络安全规则:
在res/xml/network_security_config.xml中添加:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="false">
        <domain includeSubdomains="true">rainfallpredictionmodel.onrender.com</domain>
    </domain-config>
</network-security-config>

然后在AndroidManifest.xml的<application>标签中引用:

android:networkSecurityConfig="@xml/network_security_config"

4. 添加OkHttp日志拦截器排查细节

通过日志拦截器查看完整请求、响应和错误信息,精准定位问题:
先在app/build.gradle的dependencies中添加依赖:

implementation "com.squareup.okhttp3:logging-interceptor:4.12.0"

修改OkHttpClient配置:

val loggingInterceptor = HttpLoggingInterceptor().apply {
    level = HttpLoggingInterceptor.Level.BODY
}

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS) // 延长超时适配Render实例唤醒
    .readTimeout(60, TimeUnit.SECONDS)
    .writeTimeout(60, TimeUnit.SECONDS)
    .addInterceptor(loggingInterceptor)
    .build()

查看Logcat日志,确认请求是否正确发送,以及具体错误原因(如DNS解析失败、证书错误等)。

5. 确认请求格式与后端匹配

检查后端是否接受JSON格式POST请求:若后端期望表单参数(application/x-www-form-urlencoded),需修改Retrofit接口:

interface RainfallService {
    @FormUrlEncoded
    @POST("predict/rainfall")
    fun predictRainfall(
        @Field("state") state: String,
        @Field("year") year: String
    ): Call<RainfallResponse>
}

调用时直接传入参数即可,无需使用@Body。

6. 排除网络环境干扰

测试时关闭VPN、代理,切换到移动网络或稳定WiFi,避免网络环境导致的连接失败。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:55:53