您好,我是 Android Retrofit 框架的新手。我可以使用它从 REST 服务获取 JSON 响应,但我不知道如何使用改造下载 png。我正在尝试从此网址下载 png:http://wwwns.akamai.com/media_resources/globe_emea.png http://wwwns.akamai.com/media_resources/globe_emea.png。
应该在 Callback 中指定响应对象来实现此目的。
当然我们通常使用Picasso加载图像,但有时我们确实需要使用Retrofit要加载特殊图像(例如获取验证码图像),您需要为请求添加一些标头,从响应标头中获取一些值(当然您也可以使用Picasso + OkHttp,但在项目中您已经使用Retrofit来处理大部分网络请求),所以这里介绍如何通过Retrofit 2.0.0实现(我已经在我的项目中实现了)。
关键是你需要使用okhttp3.ResponseBody
接收响应,否则 Retrofit 会将响应数据解析为 JSON,而不是二进制数据。
codes:
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
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)