关于接口的声明与回调

 
public class HttpUtils {

    private HttpListener httpListener;

    private static HttpUtils httpUtils;
    public static HttpUtils getInstence(){

        if(httpUtils == null){

            httpUtils = new HttpUtils();

        }
        return httpUtils;
    }


    public void getdata(String url){
        MyAsyanc myAsyanc = new MyAsyanc() ;
        myAsyanc.execute(url);
    }

    class MyAsyanc extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {
            String json = "";
            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                int rescode = urlConnection.getResponseCode();
                if (rescode == 200){
                    InputStream inputStream = urlConnection.getInputStream();
                    json = inputStreamTostring(inputStream);

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

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            httpListener.getJsondata(s);

        }
    }

    private String inputStreamTostring(InputStream inputStream) throws Exception {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String string = null;
        StringBuilder builder = new StringBuilder();
        while((string = bufferedReader.readLine()) != null){
            builder.append(string);
        }
        bufferedReader.close();
        return builder.toString();
    }

    public interface HttpListener{
        void getJsondata(String jsons);
    }
    public void setHttpListner(HttpListener httpListner){
      this.httpListener = httpListner;
    };

}
 
 

回调的方法


httpUtils = httpUtils.getInstence();
httpUtils.getdata(path);

httpUtils.setHttpListner(new HttpUtils.HttpListener() {
    @Override
    public void getJsondata(String jsons) {
        Gson gson = new Gson();
        MyBean myBean = gson.fromJson(jsons, MyBean.class);
        List<MyBean.ResultBean.DataBean> list = myBean.getResult().getData();

    }
});

猜你喜欢

转载自blog.csdn.net/big_fff/article/details/80684293