You need to enable JavaScript to run this app. 如何在Android应用中通过WordPress REST API获取文章特色图链接并使用?
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android应用中通过WordPress REST API获取文章特色图链接并使用?

Android集成WordPress REST API功能开发问题

已梳理的实现流程

  • 通过WordPress REST API接口拉取博客文章列表,接口返回结果为JSON数组
  • 遍历每篇文章的JSON对象,从Links -> WpFeaturedmedia -> 数组第0项 -> Href路径提取特色图索引链接
  • 将索引链接传递给列表适配器
  • 在适配器内针对索引链接发起Retrofit二次请求,从响应结构MediaDetails -> Sizes -> Thumbnail -> SourceUrl中提取可直接加载的缩略图地址
  • 拿到缩略图地址后传入Glide,完成列表项图片加载
  • 为图片接口响应创建对应POJO类,完成JSON结构映射

当前阻塞点

已通过Logcat验证getImageRetrofit方法可以成功获取到图片缩略图直链,但链路无法将该链接正常传递到列表适配器的数据源中,无法完成图片渲染。

问题代码片段

package np.com.wp_restapi;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsNotice1_Activity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private LinearLayoutManager mLayoutManager;
    private ArrayList<Model> list;
    private RecyclerViewAdapter adapter;

    private String baseURL = "http:////example.com/";

    public static List<WPPost> mListPost;
    private static Retrofit retrofit = null;
    private static String ImageHref=null;

    @Nullable
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_notice_1);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        mLayoutManager = new LinearLayoutManager(NewsNotice1_Activity.this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(mLayoutManager);

        list = new ArrayList<Model>();

        progressBar.setVisibility(View.VISIBLE);
        if (mListPost != null) {
            /// call retrofill
            getRetrofit();
        } else {
            progressBar.setVisibility(View.GONE);
        }

        adapter = new RecyclerViewAdapter(list, NewsNotice1_Activity.this);
        recyclerView.setAdapter(adapter);
    }

    public void getRetrofit() {
        Log.d(TAG, "i am inside_200");

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseURL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
        Call<List<WPPost>> call = service.getPostInfo();

        call.enqueue(new Callback<List<WPPost>>() {
            @Override
            public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
                try {
                    Log.e("NewsNotice_Activity", " response123 " + response.body());
                    mListPost = response.body();
                    progressBar.setVisibility(View.GONE);

                    for (int i = 0; i < response.body().size(); i++) {
                        String tempImageHref = response.body().get(i).getFeaturedMedia().toString();
                        Log.e("Href", "onResponse: " + tempImageHref);

                        getImageRetrofit(tempImageHref, ImageHref);

                        Log.e("main ", " title " + response.body().get(i).getTitle().getRendered() + " " +
                                response.body().get(i).getId());

                        String tempdetails = response.body().get(i).getExcerpt().getRendered().toString();
                        String tempDate = response.body().get(i).getDate().replace("T", " ");
                        tempdetails = tempdetails.replace("<p>", "")
                                .replace("</p>", "")
                                .replace("[&hellip;]", "");

                        list.add(new Model(Model.IMAGE_TYPE, tempDate, 
                                response.body().get(i).getTitle().getRendered(),
                                tempdetails, ImageHref
                        ));
                    }
                } finally {
                    System.out.println("finally");
                }
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<List<WPPost>> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    public interface RevealCourtPlaceCallbacks {
        void onSuccess(@NonNull String value);
        void onError(@NonNull Throwable throwable);
    }

    private void getImageRetrofit(final String tempImageHref, final String ImageHref) {
        Log.e("getImageRetrofit", "called " + tempImageHref);
        retrofit = new Retrofit.Builder()
               .baseUrl(baseURL)
               .addConverterFactory(GsonConverterFactory.create())
               .build();

        RetrofitArrayApi service1 = retrofit.create(RetrofitArrayApi.class);
        Call<WPPostImage> callImage = service1.getImageInfo(tempImageHref);

        callImage.enqueue(new Callback<WPPostImage>() {
            @Override
            public void onResponse(Call<WPPostImage> call, Response<WPPostImage> response) {
               Log.e("ImageInfo1","info1: "+response.body().getMediaDetails().getSizes().getThumbnail().getSourceUrl());
            }

            @Override
            public void onFailure(Call<WPPostImage> call, Throwable t) {
                Log.e("Link Failed: ", t.getMessage());
                t.printStackTrace();
            }
        });
    }

    public static List<WPPost> getList() {
        return mListPost;
    }
}

核心缺陷说明

  • 异步时序错位:Retrofit网络请求为异步执行逻辑,当前代码在循环中调用getImageRetrofit后,未等待网络回调返回,就直接将值为null的全局静态变量ImageHref传入Model构造方法完成列表项添加,此时图片请求还未返回结果,所有列表项拿到的图片链接均为空。
  • 传参逻辑无效:getImageRetrofit定义的ImageHref为方法入参,Java值传递机制下,方法内部的赋值操作不会修改外部作用域的变量,全程没有建立图片值的回传通道。
  • 值未落地存储:getImageRetrofit的回调中仅打印了获取到的图片直链日志,没有将值做任何存储,链路完全断开。
  • 全局变量数据串台:使用静态全局变量ImageHref存储单列表项的图片链接,多列表项并发请求时会出现数据覆盖、错位问题。
  • 编译错误:代码中直接使用未定义的TAG常量、okHttpClient实例,会导致编译不通过。
  • BaseUrl格式错误:当前配置的baseURL = "http:////example.com/"存在多余斜杠,会导致请求路径拼接异常。

修正方向

  1. 调整数据流逻辑:不再在文章列表请求的循环里同步发起图片请求,先将所有文章的基础信息存入列表,再针对每一项单独发起图片请求,拿到直链后更新对应列表项的图片字段,触发适配器局部刷新。
  2. 移除全局静态的图片链接变量,将图片字段直接绑定到对应的Model对象上,避免多请求场景下的数据覆盖。
  3. 修正Retrofit的BaseUrl格式,保证路径拼接正常。
  4. 可通过WordPress REST API的文章接口关联逻辑,在文章接口响应中直接获取图片直链,减少二次请求的开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.29 10:06:05