问题描述
我是Android的Retrofit框架的新手.我可以使用它从REST服务获得JSON响应,但是我不知道如何使用翻新方式下载png.我正在尝试从以下网址下载png: http://wwwns.akamai.com/media_resources/globe_emea.png .要实现此目的,应在Callback<>中指定什么是响应对象.
Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to download a png using retrofit. I am trying to download the png from this url: http://wwwns.akamai.com/media_resources/globe_emea.png.What should be response Object to be specified in the Callback<> to achieve this.
推荐答案
如上所述,您不应使用Retrofit来实际下载图像本身.如果您的目标是仅下载内容而不显示内容,则可以简单地使用Http客户端,例如 OkHttp 这是Square的另一个图书馆.
As mentioned you shouldn't use Retrofit to actually download the image itself. If your goal is to simply download the content without displaying it then you could simply use an Http client like OkHttp which is another one of Square's libraries.
下面是几行代码,您可以下载此图像.然后,您可以从InputStream中读取数据.
Here's a few lines of code which would have you download this image. You could then read the data from the InputStream.
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://wwwns.akamai.com/media_resources/globe_emea.png")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
System.out.println("request failed: " + e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
response.body().byteStream(); // Read the data from the stream
}
});
即使Retrofit并不是解决问题的人,但Interface定义的签名还是需要这样的.但同样不要这样做.
Even though Retrofit isn't the man for the job to answer your question, the signature of your Interface definition would like this. But again don't do this.
public interface Api {
@GET("/media_resources/{imageName}")
void getImage(@Path("imageName") String imageName, Callback<Response> callback);
}
这篇关于改装API以检索png图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!