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

Retrofit的call.enque()无法获取响应:Shopify CollectionListing API调用问题

问题分析与解决方案

你遇到的核心问题是Retrofit声明的返回类型和API实际返回的JSON结构不匹配,导致解析失败,所以无法获取到响应内容。

先看API返回的JSON结构:

{
  "product_ids": [
    1331092619350,
    1331125551190,
    1331126599766,
    1331121651798
  ]
}

这是一个外层对象包裹数组的结构,但你的Retrofit接口直接声明返回Call<List<Integer>>,Retrofit会尝试把整个JSON直接解析成List,这和实际结构完全不符,自然拿不到数据。

具体修改步骤:

  1. 修改ApiInterface的返回类型
    把原来的Call<List<Integer>>改成Call<IdExample>,你的IdExample类正好对应了API返回的外层JSON结构:

    public interface ApiInterface {
        @GET("collection_listings/{collection_listing_id}/product_ids.json")
        Call<IdExample> getProductIds(@Header("Authorization") String accessToken, @Path("collection_listing_id") long id);
    }
    
  2. 调整Activity中的Callback逻辑
    同步修改Callback的泛型为IdExample,然后通过response.body().getProductIds()获取实际的ID列表:

    private void processProductIds() {
        apiInterface = APIClient.getClient().create(ApiInterface.class);
        Call<IdExample> call = apiInterface.getProductIds(key, id);
        call.enqueue(new Callback<IdExample>() {
            @Override
            public void onResponse(Call<IdExample> call, Response<IdExample> response) {
                if (response.isSuccessful() && response.body() != null) {
                    List<Integer> productIds = response.body().getProductIds();
                    String s = String.valueOf(productIds);
                    Log.d("S", "onResponse:" + s);
                } else {
                    // 打印响应码辅助排查问题
                    Log.d("S", "Request failed, code: " + response.code());
                }
            }
    
            @Override
            public void onFailure(Call<IdExample> call, Throwable t) {
                // 一定要打印异常信息,否则出问题无法定位原因
                Log.e("S", "Request failed", t);
            }
        });
    }
    
  3. 额外建议

    • 务必保留onFailure中的异常日志,后续如果遇到网络问题、token格式问题等,能快速定位根源。
    • 再核对下Authorization头的格式:Shopify API通常要求Basic <base64编码的API密钥:密码>格式,虽然你Postman能正常请求,但多一层确认更稳妥。

这样修改后,Retrofit就能正确解析API返回的JSON结构,你也能顺利拿到product_ids列表了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:40:24