如何将 httpUrlConnection 与 glide 一起使用

How can I use httpUrlConnection with glide

我想使用它的各种方法,如 setRequestMethod、setRequestProperty

这是一段代码,我需要使用 glide 库而不是异步任务来实现它

提前致谢。

public class ImageLoadingAsyncTask extends AsyncTask<Integer, Void, Void> {
        Bitmap bmp;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pb_imageProgressBar.setVisibility(VISIBLE);
        }

        @Override
        protected Void doInBackground(Integer... integers) {

            String url = PrefManager.getInstanceUrl()
                    + "clients/"
                    + integers[0]
                    + "/images?maxHeight=120&maxWidth=120";
            Log.d("ashu",url);
            try {
                HttpURLConnection httpURLConnection = (HttpURLConnection) (new URL(url))
                        .openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setRequestProperty(MifosInterceptor.HEADER_TENANT,
                        "default");
                httpURLConnection.setRequestProperty(MifosInterceptor.HEADER_AUTH,
                        PrefManager.getToken());
                httpURLConnection.setRequestProperty("Accept", "application/octet-stream");
                httpURLConnection.setDoInput(true);
                httpURLConnection.connect();
                InputStream inputStream = httpURLConnection.getInputStream();
                bmp = BitmapFactory.decodeStream(inputStream);
                httpURLConnection.disconnect();
            } catch (MalformedURLException e) {
            } catch (IOException ioe) {
            }
            return null;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            if (bmp != null) {
                iv_clientImage.setImageBitmap(bmp);
            } else {
                iv_clientImage.setImageDrawable(
                        ContextCompat.getDrawable(getActivity(), R.drawable.ic_launcher));
                pb_imageProgressBar.setVisibility(GONE);
            }

        }
    }

使用Glide不需要HttpUrlConnection,直接调用Glide即可。

String url = PrefManager.getInstanceUrl()
                    + "clients/"
                    + integers[0]
                    + "/images?maxHeight=120&maxWidth=120";

GlideUrl glideUrl = new GlideUrl(url, new LazyHeaders.Builder()
                .addHeader((MifosInterceptor.HEADER_TENANT, "default")
                .addHeader(MifosInterceptor.HEADER_AUTH, PrefManager.getToken())
                .addHeader("Accept", "application/octet-stream")
                .build());
Glide.with(getActivity()).load(glideUrl).into(iv_clientImage);