网络请求工具类

 //2.声明接口变量
    private  ICallBacks iCallBacks;

    //3.定义带参构造方法
    public MyTask(ICallBacks iCallBacks) {
        this.iCallBacks = iCallBacks;
    }

    @Override
    protected String doInBackground(String... strings) {
        String str="";
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setReadTimeout(5000);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200){
                InputStream inputStream = urlConnection.getInputStream();
                str=toJson(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //4.调用接口的方法
        iCallBacks.getJsonData(s);

    }


    //1.定义一个内部接口
    public interface  ICallBacks{
        //得到json串
        void getJsonData(String jsonstr);
    }

    private String toJson(InputStream inputStream) {
        StringBuilder builder = new StringBuilder();
        String string;
        InputStreamReader in = new InputStreamReader(inputStream);
        BufferedReader reader = new BufferedReader(in);
        try {
            while ((string=reader.readLine())!=null){
                builder.append(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();

    }

  ViewHolder viewHolder = null;
        if (view==null){
            view= View.inflate(context, R.layout.item,null);
            viewHolder = new ViewHolder1();
            viewHolder.img = view.findViewById(R.id.img);
            viewHolder.title = view.findViewById(R.id.title);
            view.setTag(viewHolder);
        }else{
            viewHolder= (ViewHolder) view.getTag();
        }
        viewHolder.title.setText(results.get(i).getTitle());

        //取出image网址
        ImageLoader.getInstance().displayImage(results.get(i).getPicUrl(), viewHolder.img, options);


        return view;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值