如何使用okhttp将验证代码放到imageView中?

时间:2017-01-03 14:12:53

标签: android bitmap imageview inputstream okhttp3

Request request = new Request.Builder()
                   .url(url)
                   .addHeader("Cookie", "JSESSIONID="+sessionId)
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
    InputStream inputStream = response.body().byteStream();
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    imageView.setImageBitmap(bitmap);
}

我使用okhttp3构建一个包含cookie和session的请求,而response.body()是验证代码。 inputStream不为空,但位图为空。我尝试过以下方式,但位图也是空的。

private Bitmap convertBitmap(final Response response) throws IOException {
    InputStream inputStream = response.body().byteStream();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    byte[] bmp_buffer;
    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inputStream.close();
    bmp_buffer = outStream.toByteArray();
    return BitmapFactory.decodeByteArray(bmp_buffer, 0, bmp_buffer.length);
}

1 个答案:

答案 0 :(得分:0)

我建议您使用 Picasso 直接在ImageView中下载图片。

Picasso 库的主页示例:

String imgUrl = "http://i.imgur.com/DvpvklR.png";
Picasso.with(context).load(imgUrl).into(imageView);

另外,您可以在图像下载时添加占位符:

Picasso.with(context).load(imgUrl).placeholder(R.drawable.placeholder).into(imageView);

如果下载失败,请输入错误图片:

Picasso.with(context).load(imgUrl).error(R.drawable.error_image).into(imageView);

使用Cookie的完整代码:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor {  

    @Override  
    public Response intercept(Chain chain) throws IOException {  
        Request.Builder request = chain.request().newBuilder();  
        request.addHeader("Cookie", "JSESSIONID="+sessionId);  
        return chain.proceed(request.build());  
    }  
});  

CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);

// Create the downloader for Picasso to use
OkHttpDownloader downloader = new OkHttpDownloader(client);
Picasso picasso = new Picasso.Builder(context).downloader(downloader).build();

picasso.load(imgUrl).placeholder(R.drawable.placeholder).error(R.drawable.error_image).into(imageView);