HttpURLConnection的小Demo

来源:互联网 发布:delphi登陆淘宝联盟 编辑:程序博客网 时间:2024/05/19 05:40



最终实现效果:listView显示条目



//布局

 <ListView
       android:id="@+id/list_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

</ListView>



//每一条item的布局(供参考)

 <ImageView
        android:layout_margin="10dp"
        android:padding="10dp"
        android:id="@+id/image_view_item"
        android:layout_width="60dp"
        android:layout_height="60dp"
        />

    <TextView
        android:layout_margin="10dp"
        android:padding="10dp"
        android:layout_toRightOf="@id/image_view_item"
        android:id="@+id/tv_title_item"
        android:textSize="25sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="22222"/>

    <TextView
        android:layout_toRightOf="@id/image_view_item"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:layout_below="@id/tv_title_item"
        android:textSize="20sp"
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1111"/>


    <TextView
        android:textColor="#ff0526"
        android:id="@+id/tv_number"
        android:layout_margin="10dp"
        android:padding="10dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="33333"/>


//清单文件配置

<uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>


//请求字符串的一个Bean类

public class RootBean {

    private NewslistEntity newslist;

    public void setNewslist(NewslistEntity newslist) {
        this.newslist = newslist;
    }

    public NewslistEntity getNewslist() {
        return newslist;
    }

    public static class
    NewslistEntity {
     

        private List<NewsEntity> news;

        public void setNews(List<NewsEntity> news) {
            this.news = news;
        }

        public List<NewsEntity> getNews() {
            return news;
        }

        public static class NewsEntity {
        
            private String title;
            private String detail;
            private String comment;
            private String image;

            public void setTitle(String title) {
                this.title = title;
            }

            public void setDetail(String detail) {
                this.detail = detail;
            }

            public void setComment(String comment) {
                this.comment = comment;
            }

            public void setImage(String image) {
                this.image = image;
            }

            public String getTitle() {
                return title;
            }

            public String getDetail() {
                return detail;
            }

            public String getComment() {
                return comment;
            }

            public String getImage() {
                return image;
            }
        }
    }
}


//适配器,适配内容

public class MyBase extends BaseAdapter{
    private Context context;
    private List<RootBean.NewslistEntity.NewsEntity> list;

    public MyBase(Context context, List<RootBean.NewslistEntity.NewsEntity> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;

        if (view == null) {

            holder = new ViewHolder();

            view = view.inflate(context, R.layout.item, null);

            holder.image_view_item = (ImageView) view.findViewById(R.id.image_view_item);

            holder.tv_title_item = (TextView) view.findViewById(R.id.tv_title_item);

            holder.tv_content = (TextView) view.findViewById(R.id.tv_content);

            holder.tv_number = (TextView) view.findViewById(R.id.tv_number);

            view.setTag(holder);

        } else {

            holder = (ViewHolder) view.getTag();

        }


        holder.tv_title_item.setText(list.get(i).getTitle());

        holder.tv_content.setText(list.get(i).getDetail());

        holder.tv_number.setText(list.get(i).getComment());

        ImageLoaderUtils.setImageView(list.get(i).getImage(), context, holder.image_view_item);

        return view;
    }
    static class ViewHolder {
        TextView tv_title_item, tv_content, tv_number;
        ImageView image_view_item;

    }
}


/////加载图片的工具类

public class ImageLoaderUtils {
   public static void setImageView(String url, Context context, ImageView imageView) {
    //初始化
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
    //创建Imageloader 对象
    ImageLoader imageLoader = ImageLoader.getInstance();
    //设置初始化
    imageLoader.init(config);


    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.mipmap.ic_launcher) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.mipmap.ic_launcher)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.mipmap.ic_launcher)  //设置图片加载/解码过程中错误时候显示的图片
            .cacheInMemory(true)//设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)//设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型
            .build();//构建完成

    imageLoader.displayImage(url, imageView, options);


}


}

//判断是否有网络

public class Utils {


        /**
         * 判断是否有网络
         * @param activity
         * @return
         */
        public static boolean isNet(Activity activity) {
            ConnectivityManager connectManager = (ConnectivityManager)activity.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netWorkInfo = connectManager.getActiveNetworkInfo();
            if(netWorkInfo!=null){
                return true;
            }
            return false;
        }

        /**
         * 无网状态下询问是否打开网络
         * @param context
         */
        public static void openNet(final Context context){
            ConnectivityManager connectManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netWorkInfo = connectManager.getActiveNetworkInfo();
            if(netWorkInfo==null){
                AlertDialog.Builder dialog=new AlertDialog.Builder(context);
                dialog.setMessage("确定要打开Wifi吗?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(android.os.Build.VERSION.SDK_INT>10){
                                    Intent intent=new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                                    context.startActivity(intent);
                                    dialog.cancel();
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
            }
        }

    }



//搭建好环境,开始操作

 private static final String TAG = MainActivity.class.getSimpleName();
    private ListView list_view;
    private String data;
    private List<RootBean.NewslistEntity.NewsEntity> list;
    private MyBase adapter;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            list_view.setAdapter(adapter);

        }
    };
   
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list_view = (ListView) findViewById(R.id.list_view);

        final Gson gson = new Gson();

        list = new ArrayList<>();


        new Thread(new Runnable() {
            @Override
            public void run() {
                data = getData();

                Log.e(TAG, "run: " + data);

                RootBean rootBean = gson.fromJson(data, RootBean.class);

                RootBean.NewslistEntity newslist = rootBean.getNewslist();

                List<RootBean.NewslistEntity.NewsEntity> news = newslist.getNews();

                list.addAll(news);

                adapter = new MyBase(MainActivity.this, list);

                handler.sendEmptyMessage(1);


            }
        }).start();


        boolean net = Utils.isNet(this);
        if (net) {
            Toast.makeText(MainActivity.this, "有网!!请放心上线", Toast.LENGTH_LONG).show();
        } else {
            Utils.openNet(this);
        }


        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Nullable
    private String getData() {
        try {
            URL url = new URL("http://huixinguiyu.cn/Assets/js/newsnew.js");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(1024 * 8);

            connection.setReadTimeout(1024 * 8);

            connection.setRequestMethod("GET");

            int responseCode = connection.getResponseCode();


            if (responseCode == 200) {

                InputStream inputStream = connection.getInputStream();

                int len = 0;
                //缓冲区  一次读取1024*8
                byte[] buf = new byte[1024 * 8];

                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                while ((len = inputStream.read(buf)) != -1) {

                    baos.write(buf, 0, len);

                }

                baos.close();
                return baos.toString();


            } else {
                Log.e(TAG, "onCreate: Error" + responseCode);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

   
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Main Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

       
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }