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

Android中Retrofit调用登录注册API遇HTTP 404错误求助

排查Retrofit调用API出现HTTP 404的问题

嘿,我来帮你搞定这个404的麻烦!Postman能正常请求但Android端不行,大概率是几个容易忽略的细节问题,咱们一步步排查:


1. 检查Base URL与接口路径的拼接逻辑

你当前的Base URL是http://192.168.1.117/info/,要重点确认Retrofit接口注解里的路径写法:

  • 如果Postman里的完整请求URL是http://192.168.1.117/info/api/login,那你的接口方法应该写成@POST("api/login")
  • 绝对不要写成@POST("/api/login")——开头的斜杠会直接覆盖Base URL的末尾部分,导致拼接出错误的URL(比如变成http://192.168.1.117/api/login),这是404最常见的诱因。

2. 确认设备与服务器处于同一局域网

你用的是局域网IP192.168.1.117,要确保:

  • 你的Android真机和运行API的电脑连接的是同一个WiFi网络
  • 如果用的是Android Studio自带模拟器,需要把IP换成10.0.2.2(模拟器的127.0.0.1指向自身,而非你的电脑)

3. 检查Android网络权限与明文访问限制

网络权限

确保AndroidManifest.xml中添加了网络权限:

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

明文HTTP访问(Android 9+)

Android 9及以上默认禁止明文HTTP请求,你需要做以下配置:

  • 在res/xml目录下创建network_security_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.1.117</domain>
    </domain-config>
</network-security-config>
  • 在AndroidManifest.xml的application标签中引用该配置:
android:networkSecurityConfig="@xml/network_security_config"

(测试环境也可以直接在application标签添加android:usesCleartextTraffic="true",正式环境建议切换为HTTPS)

4. 打印完整请求日志对比Postman

给Retrofit添加OkHttp日志拦截器,查看实际发送的请求细节,和Postman的请求做对比:

第一步:添加依赖

在build.gradle(Module级)中添加日志拦截器依赖:

implementation 'com.squareup.okhttp3:logging-interceptor:4.11.0'

第二步:配置拦截器

修改ApiClient的getApiClient()方法:

public static Retrofit getApiClient() {
    if (retrofit == null) {
        // 添加日志拦截器
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY); // 打印完整请求响应
        
        OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(logging)
            .build();

        retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.117/info/")
            .client(client) // 绑定OkHttp客户端
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }
    return retrofit;
}

然后在Logcat中查看完整的请求URL、请求体、响应状态,和Postman的请求逐一对比,就能快速定位差异。

5. 验证请求方法与参数格式一致性

确认Retrofit接口的请求方法(POST/GET)、参数传递方式(Form表单/JSON)和Postman完全匹配:

  • 如果Postman用的是form-data或x-www-form-urlencoded,Retrofit接口应该用@FormUrlEncoded+@Field注解
  • 如果Postman用的是JSON请求体,Retrofit应该用@Body注解传递实体类
    参数格式不匹配也可能导致服务器路由无法匹配,触发404(部分服务器路由会严格校验请求格式)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:35:06