Imageloader+banner网络请求

来源:互联网 发布:揭秘淘宝衣服进货渠道 编辑:程序博客网 时间:2024/04/30 14:26

compile ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’
compile ‘com.youth.banner:banner:1.4.9’

```public class MainActivity extends AppCompatActivity {    private String urlPath = "http://zkread.com/htnewsroom/articles/tops";    private Handler mHandler=new Handler(){        @Override        public void handleMessage(Message msg) {            Data data = new Gson().fromJson(msg.obj.toString(),Data.class);            List<Data.DataBean> listBeans = data.getData();            List<String> images=new ArrayList<>();            for(Data.DataBean bean:listBeans){                images.add(bean.getImgSrc());            }            //设置图片资源            banner.setImages(images);            //开启轮询            banner.start();        }    };    private Banner banner;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        loadData();    }    private void initView() {        banner= (Banner) findViewById(R.id.banner);        //设置图片加载器        banner.setImageLoader(new BannerImageLoader(this));        //设置显示样式        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);        //设置圆点位置  左右中        banner.setIndicatorGravity(BannerConfig.LEFT);         //设置动画        banner.setBannerAnimation(Transformer.ScaleInOut);    }    private void loadData() {        new Thread(){            @Override            public void run() {                String result = UrlUtils.getUrlConnect(urlPath);                Log.e("run", "run: "+result );                Message msg= Message.obtain();                msg.what=1;                 msg.obj=result;                mHandler.sendMessage(msg);            }        }.start();    }}----------public class BannerImageLoader extends com.youth.banner.loader.ImageLoader{    private ImageLoader imageloader;    private DisplayImageOptions options;    public BannerImageLoader(Context context) {        //创建默认的ImageLoader配置参数        ImageLoaderConfiguration configuration = ImageLoaderConfiguration                .createDefault(context);        //将configuration配置到imageloader中        imageloader= ImageLoader.getInstance();        imageloader.init(configuration);        options=new DisplayImageOptions.Builder()                .cacheInMemory(true)                .cacheOnDisk(true)                .bitmapConfig(Bitmap.Config.ARGB_8888)                .showImageOnLoading(R.mipmap.ic_launcher)                .showImageForEmptyUri(R.mipmap.ic_launcher)                .showImageOnFail(R.mipmap.ic_launcher)                .imageScaleType(ImageScaleType.EXACTLY)                .build();    }    @Override    public void displayImage(Context context, Object path, ImageView imageView) {//        Resources resources = context.getResources();//        DisplayMetrics dm = resources.getDisplayMetrics();//        float density = dm.density;//        int width = dm.widthPixels;//        int height = dm.heightPixels;//        ImageSize imageSize=new ImageSize(1000,600);          imageloader.displayImage(path.toString(),imageView,options);        Glide.with(context).load(path).into(imageView);    }}----------public class UrlUtils {    /**         * HttpURLConnection的post请求         * @param urlPath         * @param map         * @return         */        public static String postUrlConnect(String urlPath, Map<String,Object> map){           StringBuffer sbRequest =new StringBuffer();            if(map!=null&&map.size()>0){                for (String key:map.keySet()){                    sbRequest.append(key+"="+map.get(key)+"&");                }            }            String request = sbRequest.substring(0,sbRequest.length()-1);            try {                //创建URL                URL url = new URL(urlPath);                //由URL的openConnection方法得到一个HttpURLConnection(需要强转)                HttpURLConnection httpURLConnection =                        (HttpURLConnection) url.openConnection();                //设置post提交                httpURLConnection.setRequestMethod("POST");                //设置超时时间                httpURLConnection.setConnectTimeout(30000);                httpURLConnection.setReadTimeout(30000);                httpURLConnection.setDoInput(true);                httpURLConnection.setDoOutput(true);                //把请求正文通过OutputStream发出去                OutputStream os =httpURLConnection.getOutputStream();                os.write(request.getBytes());                os.flush();                //判断响应码  200 代表成功                if(httpURLConnection.getResponseCode()==200){                    //由HttpURLConnection拿到输入流                    InputStream in=httpURLConnection.getInputStream();                    StringBuffer sb=new StringBuffer();                    //根据输入流做一些IO操作                    byte [] buff =new byte[1024];                    int len=-1;                    while((len=in.read(buff))!=-1){                        sb.append(new String(buff,0,len,"utf-8"));                    }                    in.close();                    os.close();                    httpURLConnection.disconnect();                    return  sb.toString();                }else{                    return null;                }            }catch (Exception e){                Log.e("post","code:"+e.getMessage());                return null;            }        }        /**         * HttpURLConnection的get请求         * @param urlPath         * @return         */        public static String getUrlConnect(String urlPath){            try {                //创建URL                URL url = new URL(urlPath);                //由URL的openConnection方法得到一个HttpURLConnection(需要强转)                HttpURLConnection httpURLConnection =                        (HttpURLConnection) url.openConnection();                //设置连接                httpURLConnection.connect();                //判断响应码  200 代表成功                if(httpURLConnection.getResponseCode()==200){                    //由HttpURLConnection拿到输入流                    InputStream in=httpURLConnection.getInputStream();                    StringBuffer sb=new StringBuffer();                    //根据输入流做一些IO操作                    byte [] buff =new byte[1024];                    int len=-1;                    while((len=in.read(buff))!=-1){                        sb.append(new String(buff,0,len,"utf-8"));                    }                    in.close();                    httpURLConnection.disconnect();                    return  sb.toString();                }else{                    return null;                }            } catch (Exception e) {                e.printStackTrace();            }            return null;        }}
原创粉丝点击