1. 程式人生 > >AsyncTask介面,網路請求,方法類

AsyncTask介面,網路請求,方法類

public class HttpUtils {
    public static boolean isWork(Context context){
        if(context!=null){
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
            if(info!=null){
                return info.isAvailable();
            }
        }
        return false;
    }

    public static void httpAsynTask(String strUrl, final CallBackString backString) {
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                return httpGet(strings[0]);
            }
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                //介面回撥的方法
                backString.getData(s);
            }
        }.execute(strUrl);
    }
    //介面================================
    public interface  CallBackString{
        void   getData(String s);
    }
    public  static String httpGet(String strUrl) {
        //設定url
        try {
            URL url = new URL(strUrl);
            //獲取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //設定為get請求
            connection.setRequestMethod("GET");
            //設定連線主機超時時間
            connection.setConnectTimeout(5000);
            //設定從主機讀取資料超時
            connection.setReadTimeout(5000);
            //得到資料
            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            //拼接資料
            StringBuilder builder = new StringBuilder();
            String str = "";
            while ((str = reader.readLine()) != null) {
                builder.append(str);
            }
            //關閉連線
            connection.disconnect();
            //返回資料
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}