You need to enable JavaScript to run this app. Android Studio使用Retrofit2请求restdb接口返回401/500错误如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio使用Retrofit2请求restdb接口返回401/500错误如何解决?

问题排查与修复方案

核心错误点

  • 接口固定请求头中的x-apikey值为占位符heregoestheapikey,你在MainActivity中定义的有效apikey变量未被实际传入请求,直接触发401未授权错误。
  • 错误配置GET请求的Content-Type:application/x-www-form-urlencoded是POST表单请求专属头参数,GET请求携带该头会导致服务端解析参数异常,触发500错误。
  • 可选注意点:restdb的查询接口默认返回数组格式,如果你的查询参数匹配多条结果,用Call<Usuario>单个对象接收会导致Gson解析失败。
  • 小问题:代码中所有Toast都未调用.show()方法,不会弹出提示,调试时可补上。

修复代码示例

UsuarioAPI接口修改

@Headers({
    "User-Agent: my-restdb-app",
    "Accept: application/json", 
    "cache-control: no-cache"
})
@GET("rest/usuarios")
// 动态传入x-apikey头,返回值改为列表适配接口返回结构
Call<List<Usuario>> find(@Query("nombre") String nombre, @Header("x-apikey") String apikey);

MainActivity请求逻辑修改

private void find(String codigo){
    String apikey = "9dc3afb8b6087192d5e9e50c5f2cb44927be5";

    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://adaptai-eea8.restdb.io/")
            .addConverterFactory(GsonConverterFactory.create()).build();

    UsuarioAPI usuarioAPI = retrofit.create(UsuarioAPI.class);
    // 调用时传入实际apikey
    Call<List<Usuario>> call = usuarioAPI.find(codigo, apikey);
    call.enqueue(new Callback<List<Usuario>>() {
        @Override
        public void onResponse(Call<List<Usuario>> call, Response<List<Usuario>> response) {
            try {
                if(response.isSuccessful()){
                    List<Usuario> usuarioList = response.body();
                    if(usuarioList != null && !usuarioList.isEmpty()){
                        Usuario u = usuarioList.get(0);
                        textView.setText(u.getContra());
                        Log.d("Funciona", u.getContra());
                    }
                }
            }catch(Exception ex){
                Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<List<Usuario>> call, Throwable t) {
            Toast.makeText(MainActivity.this, "Error de conexión", Toast.LENGTH_SHORT).show();
        }
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 23:15:02