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

Android开发:使用Picasso加载网络图片时传递请求头的方法

在Picasso中加载网络图片时添加请求头的实现方式

嘿,这个需求我刚好处理过!Picasso本身并没有提供直接设置请求头的API,但我们可以通过结合OkHttp拦截器来轻松实现,下面是具体的步骤:

1. 确保依赖到位

先确认项目里已经引入了Picasso和OkHttp的依赖(Picasso 2.5.2及以上版本默认依赖OkHttp,但自定义Client时还是要确保OkHttp依赖存在):

implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.squareup.okhttp3:okhttp:4.10.0'

2. 编写OkHttp拦截器添加请求头

我们需要创建一个拦截器,在每次图片请求发送前插入自定义的请求头:

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

public class ImageHeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 获取原始请求对象
        Request originalRequest = chain.request();
        
        // 构建新请求,添加自定义头部(这里可以加多个)
        Request modifiedRequest = originalRequest.newBuilder()
                .addHeader("Authorization", "Bearer your_access_token") // 示例:身份验证头
                .addHeader("X-Custom-Header", "your_custom_value") // 自定义业务头
                .build();
        
        // 执行修改后的请求并返回响应
        return chain.proceed(modifiedRequest);
    }
}

3. 配置Picasso使用自定义OkHttpClient

接下来创建带有拦截器的OkHttpClient,再把它绑定到Picasso实例上(建议在Application类里全局配置,避免重复创建):

import com.squareup.picasso.Picasso;
import okhttp3.OkHttpClient;

// 初始化自定义OkHttpClient
OkHttpClient customOkHttp = new OkHttpClient.Builder()
        .addInterceptor(new ImageHeaderInterceptor())
        .build();

// 构建自定义Picasso实例
Picasso customPicasso = new Picasso.Builder(getApplicationContext())
        .downloader(new OkHttp3Downloader(customOkHttp))
        .build();

// 设置为全局默认的Picasso实例
Picasso.setSingletonInstance(customPicasso);

4. 正常使用Picasso加载图片

现在你就可以像平时一样调用Picasso加载图片了,所有的图片请求都会自动带上你设置的请求头:

Picasso.get()
        .load("https://your-domain.com/image.jpg")
        .placeholder(R.drawable.placeholder)
        .error(R.drawable.error)
        .into(yourImageView);

额外小提示

  • 如果需要给特定请求加不同的头部,可以在拦截器里根据请求URL做判断,或者创建多个带不同拦截器的Picasso实例。
  • 记得把示例里的your_access_token和your_custom_value替换成你实际需要的头部内容哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:05:19