您好,我是 Android 的 Retrofit 框架的新手。我可以使用它从 REST 服务获得 JSON 响应,但我不知道如何使用改造下载 png。我正在尝试从此网址下载 png: http://wwwns.akamai.com/media_resources/globe_emea.png . 应该在 Callback<> 中指定什么响应对象来实现这一点。
最佳答案
当然我们通常使用 Picasso 来加载图片,但有时我们确实需要使用 Retrofit 来加载特殊图片(例如获取验证码图片),您需要添加一些请求头,从响应头中获取一些值(当然你也可以使用Picasso + OkHttp,但是在一个项目中你已经使用Retrofit来处理大部分网络请求),所以这里介绍如何通过Retrofit 2.0实现。 0(我已经在我的项目中实现了)。
关键是你需要使用okhttp3.ResponseBody
来接收响应,否则Retrofit会将响应数据解析为JSON,而不是二进制数据。
代码:
public interface Api {
// don't need add 'Content-Type' header, it's useless
// @Headers({"Content-Type: image/png"})
@GET
Call<ResponseBody> fetchCaptcha(@Url String url);
}
Call<ResponseBody> call = api.fetchCaptcha(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
// display the image data in a ImageView or save it
Bitmap bmp = BitmapFactory.decodeStream(response.body().byteStream());
imageView.setImageBitmap(bmp);
} else {
// TODO
}
} else {
// TODO
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
// TODO
}
});
关于android - 改造 API 以检索 png 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25462523/