Skip to content

Instantly share code, notes, and snippets.

@realdadfish
Last active August 29, 2015 14:06
Show Gist options
  • Save realdadfish/8c31cd21bcd03f706af8 to your computer and use it in GitHub Desktop.
Save realdadfish/8c31cd21bcd03f706af8 to your computer and use it in GitHub Desktop.
How to use OkHttp 2.0 API to download stuff on behalf of Picasso.
public class OkHttpDownloader implements Downloader
{
@Override
public Response load(Uri uri, boolean b) throws IOException
{
HttpClientProxy clientProxy = // create a HttpClient proxy that
// forwards stuff to a real OkHttpClient
// or some mocked class
Request request = new Request.Builder()
.url(uri.toString())
.build();
com.squareup.okhttp.Response response = clientProxy.newCall(request).execute();
if (!response.isSuccessful())
{
throw new ResponseException(response.code() + " " + response.message());
}
// we could be stricter here, but this should be enough to separate non-image responses
if (!response.body().contentType().type().equals("image"))
{
throw new ResponseException("unsupported Content-Type returned: " + response.body().contentType());
}
return new Response(response.body().byteStream(), false, response.body().contentLength());
}
}
public class OkHttpPicassoProvider implements Provider<Picasso>
{
@Inject
protected Application mApplication;
private Picasso mInstance;
@Override
public synchronized Picasso get()
{
if (mInstance == null)
{
mInstance = create();
}
return mInstance;
}
private Picasso create()
{
return new Picasso.Builder(mApplication)
.downloader(new OkHttpDownloader())
.loggingEnabled(BuildConfig.DEBUG)
.listener(new Picasso.Listener()
{
@Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception)
{
Log.e("failed to load image from URI " + uri);
}
})
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment