从网络获取文本,和图片数据的工具类,

获取数据工具类代码展示如下:
···注:获取网络数据要在次线程里,耗时操作不能放在主线程里,否则会出现ANR(应用程序无响应),务必不要忘了加联网权限
public class Tools {
    //获取网络文本的方法
    public static String getText(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder s = new StringBuilder();
                String temp = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    s.append(temp);
                }
                String string = s.toString();
                return string;

            }else {
                Log.e("TAG","ss" );
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        return "";
    }

    //获取网络图片的方法
    public static Bitmap getBitmap(String urlBitmap) {
        try {
            URL url = new URL(urlBitmap);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            int code = urlConnection.getResponseCode();
            if (code==200){
                //开始获取图片
                InputStream inputStream = urlConnection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
-------------------------------------------------------------------------

以下是解析获取过来的文本数据
 
new Thread(){
    @Override
    public void run() {
        super.run();
        //获取文本数据
        String text = Tools.getText(urlString);
        //开始解析
        Gson gson = new Gson();
        Phone phone = gson.fromJson(text, Phone.class);
        //获得解析完的集合
        result = phone.getResult();
        final Message msg = new Message();
        msg.what=1;
        msg.obj=result;
        handler.sendMessage(msg);
    }
}.start();
 
 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值