PullToRefresh


XML

activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="animtest.com.example.e531.mypulltorefresh_demo.MainActivity">

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/rel_navigate"
        android:layout_alignParentBottom="true">
        <RadioButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ListView"
            android:button="@null"
            android:gravity="center"
            android:id="@+id/rb_index"
            android:padding="3dp"
            android:background="@drawable/rb_selector"
            android:checked="true"/>

        <RadioButton
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="ScrollView"
            android:button="@null"
            android:gravity="center"
            android:padding="3dp"
            android:id="@+id/rb_down"
            android:background="@drawable/rb_selector"/>

    </RadioGroup>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/rel_navigate"
        android:id="@+id/main_content"></FrameLayout>
</RelativeLayout>

item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv"/>
</LinearLayout>

pscrollview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.handmark.pulltorefresh.library.PullToRefreshScrollView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/refresh_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF">

        <!--只能有一个子孩子-->

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">


            <ImageView
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:src="@mipmap/ic_launcher"/>
            <!--listview嵌套在scrolview中,没有办法正确去计算listveiw的高度
            解决方案:自定义一个view 重写listveiew中的onMeasure方法


            -->
            <animtest.com.example.e531.mypulltorefresh_demo.MyListView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/lv"></animtest.com.example.e531.mypulltorefresh_demo.MyListView>

        </LinearLayout>


    </com.handmark.pulltorefresh.library.PullToRefreshScrollView>

</LinearLayout>

pulllistview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ptr="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!--
    ptr:ptrDrawable="@drawable/default_ptr_flip":刷新时显示的图片
    ptr:ptrAnimationStyle="flip":刷新的图片以何种方式显示出来
    ptr:ptrHeaderBackground="#383838":刷新时头部的布局的背景色
    ptr:ptrHeaderTextColor="#FFFFFF":刷新时头部字体的颜色

    还需要添加以下的命名空间
   xmlns:ptr="http://schemas.android.com/apk/res-auto"

-->


    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/plv"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF"
        ></com.handmark.pulltorefresh.library.PullToRefreshListView>
</LinearLayout>


MainActivity



import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {
    private RadioGroup radioGroup;

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

        radioGroup = (RadioGroup) findViewById(R.id.rel_navigate);
        //添加事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.rb_index:
                        //动态添加fragment
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_content,new PullListView()).commit();
                        break;

                    case R.id.rb_down:
                        getSupportFragmentManager().beginTransaction().replace(R.id.main_content,new PScrollView()).commit();
                        break;

                }
            }
        });
        //动态添加fragment
        getSupportFragmentManager().beginTransaction().replace(R.id.main_content,new PullListView()).commit();

    }
}

MyAdapter

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;


public class MyAdapter extends BaseAdapter {
    private Context context;
    private List<Result.NewslistEntity> newslist;

    public MyAdapter(Context context, List<Result.NewslistEntity> newslist) {
        this.context = context;
        this.newslist = newslist;
    }

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

    @Override
    public Object getItem(int position) {
        return newslist.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if(convertView==null){
            holder=new ViewHolder();
            convertView=View.inflate(context,R.layout.item,null);
            holder.textView =(TextView) convertView.findViewById(R.id.tv);
            convertView.setTag(holder);
        }else{
            holder=(ViewHolder) convertView.getTag();
        }
        holder.textView.setText(newslist.get(position).getTitle());
        return convertView;
    }

    class ViewHolder{
        TextView textView;
    }

}

MyListView



import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 *
 * 参考博客地址:http://blog.csdn.net/zhaokaiqiang1992/article/details/38585547
 */
public class MyListView extends ListView {
    public MyListView(Context context) {
        super(context);
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 重新计算高度
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

   /* @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }*/
}


PScrollView


import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;

import java.util.ArrayList;
import java.util.List;

import animtest.com.example.e531.mypulltorefresh_demo.utils.MyTask;

public class PScrollView extends Fragment {

    private PullToRefreshScrollView pscrollview;
    private int pageIndex=1;
    private int operType=1;//1:刷新 2:加载更多
    private String url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
    private MyAdapter adapter;
    private List<Result.NewslistEntity> datas=new ArrayList<>();
    private MyListView myListView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.pscrollview,container,false);

        pscrollview = (PullToRefreshScrollView) v.findViewById(R.id.refresh_scroll_view);
        //listview组件
        myListView = (MyListView) v.findViewById(R.id.lv);
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initPullListView();

        requestNetData();


    }
    /**
     * 请求网络数据
     */
    private void requestNetData() {
        //初使化数据
        MyTask myTask=new MyTask(new MyTask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                //进行解析
                Gson gson=new Gson();
                Result result = gson.fromJson(jsonstr, Result.class);

                if(operType==1){
                    datas.clear();

                }
                //选取列表数据
                datas.addAll(result.getNewslist());

                //设置适配器
                setAdapter();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新完成
                        pscrollview.onRefreshComplete();
                    }
                },1000);



            }
        });
        myTask.execute(url);
    }

    private void setAdapter(){
        if(adapter==null){
            adapter=new MyAdapter(getActivity(),datas);

            myListView.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
    }

    public void initPullListView(){
        //1.设置刷新模式  BOTH:支持上拉和下拉  PULL_FROM_END:支持上拉  PULL_FROM_START:支持下拉
        pscrollview.setMode(PullToRefreshBase.Mode.BOTH);
        //2.设置头尾布局的文字
        ILoadingLayout startLayout = pscrollview.getLoadingLayoutProxy(true, false);
        startLayout.setPullLabel("下拉刷新");
        startLayout.setRefreshingLabel("正在刷新");
        startLayout.setReleaseLabel("放开刷新");

        ILoadingLayout endLayout = pscrollview.getLoadingLayoutProxy(false, true);
        endLayout.setPullLabel("上拉刷新");
        endLayout.setRefreshingLabel("正在刷新");
        endLayout.setReleaseLabel("放开刷新");

        //3.设置监听
        pscrollview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //下拉刷新
                pageIndex=1;
                operType=1;
                requestNetData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //上拉加载
                pageIndex++;
                operType=2;
                requestNetData();

            }
        });


    }

}

PullListView


import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;

import animtest.com.example.e531.mypulltorefresh_demo.utils.MyTask;


public class PullListView extends Fragment {

    private int operType=1;//1:刷新 2:加载更多
    private PullToRefreshListView plv;
    private int pageIndex=1;
    private String url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
    //进行初使化
    private List<Result.NewslistEntity> newslist=new ArrayList<>();

    private MyAdapter adapter;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.pulllistview,container,false);

        plv = (PullToRefreshListView) v.findViewById(R.id.plv);

        //进行初使化
        initPullListView();
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        requestNetData();
    }

    private void setAdapter(){
        if(adapter==null){
            adapter=new MyAdapter(getActivity(),newslist);
            plv.setAdapter(adapter);
        }else{
            adapter.notifyDataSetChanged();
        }
    }

    public void requestNetData(){

        MyTask task=new MyTask(new MyTask.Icallbacks() {
            @Override
            public void updateUiByjson(String jsonstr) {
                //解析
                Gson gson=new Gson();
                Result result = gson.fromJson(jsonstr, Result.class);

                if(operType==1){
                    //newslist.clear();//清空
                    newslist.addAll(0,result.getNewslist());//将新请求的数据放在集合列表的最前面
                }else{
                    //添加到集合中
                    newslist.addAll(result.getNewslist());
                }

                //显示
                setAdapter();

                //关闭尾布局
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        plv.onRefreshComplete();
                    }
                },500);

            }
        });

        task.execute(url);

    }

    public  void initPullListView(){
        //1.设置模式  BOTH:支持上拉与下拉  PULL_FROM_START:支持下拉   PULL_FROM_END:支持上拉
        plv.setMode(PullToRefreshBase.Mode.BOTH);

        //2.设置头尾布局中的文本
        ILoadingLayout headerLayout = plv.getLoadingLayoutProxy(true, false);//第一个参数为true,代表设置头部布局中文本
        headerLayout.setPullLabel("下拉刷新...");
        headerLayout.setRefreshingLabel("正在刷新...");
        headerLayout.setReleaseLabel("松开刷新.....");

        ILoadingLayout footerLayout = plv.getLoadingLayoutProxy(false, true);//第一个参数为false,代表设置尾部布局中文本
        footerLayout.setPullLabel("加载更多...");
        footerLayout.setRefreshingLabel("正在加载...");
        footerLayout.setReleaseLabel("松开加载.....");

        //3.设置上拉与下拉的监听
        plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //下拉,刷新回调
                pageIndex=1;
                operType=1;
                requestNetData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                //上拉,加载
                pageIndex++;
                operType=2;
                requestNetData();

            }
        });

    }
}

Result

package animtest.com.example.e531.mypulltorefresh_demo;

import java.util.List;

/**
 * Created by e531 on 2017/11/15.
 */
public class Result {

    /**
     * newslist : [{"title":"江歌遇害377天: 孩子,这些时刻请不要善良","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-36271085.static/640","description":"育儿宝典","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722026&signature=IghuNIwOllH8GGy4wNvZFV7Dja7AAng*eiHkfPDD1Ao8TeHb6QcIf6aT3ZADczywYyahU7XkII1IMf1SjPWgVRCO9Q66ce44-CiuyTaus0M="},{"title":"因\u201c胸夹手机\u201d走红的俩女星,今一个演绎青春励志,一个悄无声息","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59131196.jpg/640","description":"谍报","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722026&signature=DHD7D1pUzX5iJ2jrL0c41e23xwvBqSjk2sdGTolraWXWKJvh93Ves5gqFsN39mP-dafcosBAljhLrmaTWOv8AHjy0sogZXJwLwNCwHJ6Aqk="},{"title":"刘鑫,请你好好的活下去。","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59113587.jpg/640","description":"口袋电影","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722026&signature=8yyvxIOiLNMHw5oOH0Tscbu4-ZXAgbDbY*NbwUj0nM5QXx-mgtQPjBY5*N9Kt-PTlBDPp9ZRVChSN0Hf6rC8rcie0Ud12A2-xfPC-uDvDOo="},{"title":"\u201c女人一定要舍得为自己花钱\u201d丨这种消费观把我们害得有多惨?","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59145866.jpg/640","description":"我们心里都有病","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722025&signature=gs8Qeb32NFouEkf6Jh7Bz1cwWEUikDaPB7yPyaqotlbxHE5jmZzo0CIcdKyNgCzvDUyV*z-TZYLpj5HhkSiuQ2LCKfmPk30MkTHSYe9wE4I="},{"title":"选择朋友,就是选择命运","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-58262617.jpg/640","description":"MBA智库","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722025&signature=o3t6I4fqIo*edpAa1Iw**xqo9RAdx052*6lcdD3WwQOHvAaeFacdhTzfFRtDl5nHCCR-f1nuPYuXohyUCYCCxJtnSZ3Rq5Cacvr0hw*3eaY="},{"title":"【话题】打篮球的好处可不止是可以长高,变帅!还有以下这些好处....","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-46804312.static/640","description":"篮球技巧教学","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722024&signature=fQdwG47WN96jb-Narr*Vv2HdyOWHEwBX9DK4NZ4Y0A3xsVdin*XiLU*UKjBJDpc8swhHqheAV8Tj*IeXpasJAJOpZW9w1GbdOeNHgQhqdog="},{"title":"活动丨最美HR第二季报名开始\u2014巴厘岛自由行等你来!","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59143086.jpg/640","description":"智联招聘HR公会","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722024&signature=fYpxm6cmXGwuIkDR*6BD7HDkQGk7Ne1BK--0LYs29DyV4hHS8epW7P7TnMxahKdJSflSY1UdvhJtTINLDiIm8gyDUmwtEoMdREqi5oIIZV4="},{"title":"卖药必读:姑娘,麻烦你把腿并起来!","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-45442003.jpg/640","description":"连锁药店","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722024&signature=XR*D2CRsiUuprjW-KCTEEVqsmO*54VcNXQZMXwLShjXlyvlT-CnahI0M0hl5YfiOs3xCnh*DE73GRdfUhuB7qAtQkGSJiUOUjj4cryNWD0U="},{"title":"心态好,一切都好!","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59142370.jpg/640","description":"张文魁","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722024&signature=ylmq2Mo-gt1WFPsUO0WPcrSO*DhivYoYOZ8MLrEGQQLzKtoDmdeJ9GSZizDoSZxrKxUVhDoah42msbST6KUaLgRpIF-XbP4*lHZ-KU55bhY="},{"title":"人生,没了健康,就没了一切!(深度好文)","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-59142379.jpg/640","description":"张文魁","ctime":"2017-11-15","url":"https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722023&signature=LHVpylOm3bz3tMNCmacsr84iTe0JHkleMrhiWXzsl4J8guFBBxg1QB2GWnOc72a982UzCFCzLUR4CppHLNU0Hb*W7AA6w-pbxSHqVmwLoTo="}]
     * code : 200
     * msg : success
     */
    private List<NewslistEntity> newslist;
    private int code;
    private String msg;

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

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistEntity> getNewslist() {
        return newslist;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public class NewslistEntity {
        /**
         * title : 江歌遇害377天: 孩子,这些时刻请不要善良
         * picUrl : https://zxpic.gtimg.com/infonew/0/wechat_pics_-36271085.static/640
         * description : 育儿宝典
         * ctime : 2017-11-15
         * url : https://mp.weixin.qq.com/s?src=16&ver=490&timestamp=1510722026&signature=IghuNIwOllH8GGy4wNvZFV7Dja7AAng*eiHkfPDD1Ao8TeHb6QcIf6aT3ZADczywYyahU7XkII1IMf1SjPWgVRCO9Q66ce44-CiuyTaus0M=
         */
        private String title;
        private String picUrl;
        private String description;
        private String ctime;
        private String url;

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

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getTitle() {
            return title;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public String getDescription() {
            return description;
        }

        public String getCtime() {
            return ctime;
        }

        public String getUrl() {
            return url;
        }
    }
}

MyTask



import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 使用AsyncTask+HttpURLConnection请求数据
 *
 */
public class MyTask extends AsyncTask<String,Void,String> {

    //1.申请一个接口类对象
    private  Icallbacks icallbacks;

    //将无参构造设置成私有的,使之在外部不能够调用
    private MyTask(){}

    //定义有参构造方法
    public MyTask(Icallbacks icallbacks) {
        //2.实例化
        this.icallbacks = icallbacks;
    }

    @Override
    protected String doInBackground(String... params) {
        String str="";

        try {
             //使用HttpUrlConnection
            URL url=new URL(params[0]);
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            if(connection.getResponseCode()==200){
                InputStream inputStream=connection.getInputStream();
                //调用工具类中的静态方法
                str=StreamToString.streamToStr(inputStream,"utf-8");
            }

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


        return str;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //3.调用接口
        //解析,封装到bean,更新ui组件
        icallbacks.updateUiByjson(s);
    }
    //定义一个接口
    public interface Icallbacks{
        /**
         * 根据回传的json字符串,解析并更新页面组件
         * @param jsonstr
         */
        void updateUiByjson(String jsonstr);
    }
}

StreamToString



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


public class StreamToString {

    public static String streamToStr(InputStream inputStream,String chartSet){

        StringBuilder builder=new StringBuilder();
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
            String con;
            while ((con=br.readLine())!=null){
                builder.append(con);
            }

            br.close();
            return builder.toString();


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


        return "";
    }
}



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值