HttpURLConnection网络请求

public class HttpUtils{
    private HttpUtilListener httpUtilListener;
    private static final String TAG = "HttpUtils+-------";
    private static final int SUCCESS=0;
    private static final int ERROR=1;
    private MyHandler myHandler=new MyHandler();

    //单例模式
    private static HttpUtils httpUtils=new HttpUtils();
    private HttpUtils(){}
    public static HttpUtils getInstaner(){
        if (httpUtils==null){
            httpUtils=new HttpUtils();
        }
        return httpUtils;
    }
    public void get(final String url){

        new Thread(){
            @Override
            public void run() {
                try {
                    URL u=new URL(url);
                    HttpURLConnection connection= (HttpURLConnection) u.openConnection();
                    connection.setConnectTimeout(5000);
                    int code = connection.getResponseCode();
                    if (code==200){
                        InputStream inputStream = connection.getInputStream();
                        String josn = inputStreamString(inputStream);
                        Message message = myHandler.obtainMessage();
                        message.what=SUCCESS;
                        message.obj=josn;
                        myHandler.sendMessage(message);

                    }else{
                        Message message = myHandler.obtainMessage();
                        message.what=ERROR;
                        message.obj="失败";
                        myHandler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message message = myHandler.obtainMessage();
                    message.what=ERROR;
                    message.obj=e.getMessage();
                    myHandler.sendMessage(message);
                }
            }
        }.start();
    }

    public String inputStreamString(InputStream inputStream) throws IOException {
        int len=0;
        byte[] b=new byte[1024];
        StringBuffer buffer = new StringBuffer();
        while ((len=inputStream.read(b))!=-1){
            String s = new String(b, 0, len);
            buffer.append(s);
        }
        return buffer.toString();
    }
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS:
                    String json= (String) msg.obj;
                    Log.d(TAG, "handleMessage: "+json);
                    httpUtilListener.getSuccess(json);
                    break;
                case ERROR:
                    String error= (String) msg.obj;
                    Log.d(TAG, "handleMessage: "+error);
                    httpUtilListener.getError(error);
                    break;
            }
        }
    }
    public interface HttpUtilListener{
        void getSuccess(String json);
        void getError(String error);
    }
    public void getHttpUtilListener(HttpUtilListener httpUtilListener){
        this.httpUtilListener=httpUtilListener;
    }
}
 
 
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity---------";
    private String[] new_itme={"top","shehui","guonei","guoji","yule","tiyu","junshi","keji","caijing","shishang"};
    private XListView xListView;
    private String new_url="http://v.juhe.cn/toutiao/index";
    private String type="top";
    private int i=0;
    private  List<GsonBean.ResultBean.DataBean> list=new ArrayList<>();
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化页面
        initView();
        getDataFromNet();
    }
    public void getDataFromNet() {
        //实例化httputils
        HttpUtils httpUtils = HttpUtils.getInstaner();
        //拼接url接口
        String url=new_url+"?type="+type+"&key=...........";
        //把接口传过去
        httpUtils.get(url);

        httpUtils.getHttpUtilListener(new HttpUtils.HttpUtilListener() {
            @Override
            public void getSuccess(String json) {
                //gson进行解析
                Gson gson = new Gson();
                GsonBean gsonBean = gson.fromJson(json, GsonBean.class);
                //调取里面的内容参数
                List<GsonBean.ResultBean.DataBean> list1 = gsonBean.getResult().getData();
                //判断type==top就清空集合
                if (type=="top"){
                    //清空集合
                    list.clear();
                }
                //把获取的参数赋给集合
                list.addAll(list1);
                adapter.notifyDataSetChanged();
                //判断type==top就隐藏下拉刷新   不   隐藏上啦加载
                if (type=="top"){
                    xListView.stopRefresh();
                }else{
                    xListView.stopLoadMore();
                }

            }

            @Override
            public void getError(String error) {

            }
        });
    }

    private void initView() {
        //获取资源id
        xListView=findViewById(R.id.xlistview);
        //设置可以刷新
        xListView.setPullLoadEnable(true);
        //设置可以下啦
        xListView.setPullRefreshEnable(true);
        Date d=new Date();
        xListView.setRefreshTime(d+"");

        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                //当刷新时回调
                type="top";
                getDataFromNet();
            }

            @Override
            public void onLoadMore() {
                //当上啦加载时回调

                //每次加载时i++
                i++;
                //得到new_itme数组里面的数据
                String aaa=new_itme[i];
                //赋值给type
                type=aaa;
                getDataFromNet();

            }
        });
        adapter = new MyAdapter(MainActivity.this, list);
        xListView.setAdapter(adapter);
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_41701790/article/details/80387575