封装AsyncTask成工具类

         先说一下怎么使用:

String s = new GetAsyncTaskData() {}.execute("http://169.254.168.158/mobile/index.php?act=goods&op=goods_list&page=100").get();

接着再去Gson解析就好了,但是下面的代码会等到网络获取到数据之后再进行。

public class GetNetData {
    public static String getData(String path){
        String result = null;
        try {
            URL url=new URL(path);
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            int code=conn.getResponseCode();
            Log.i("-----------", "getData: "+code);
            if (code==200){
                InputStream is=conn.getInputStream();
                ByteArrayOutputStream baos=new ByteArrayOutputStream();
                int len=-1;
                byte[] buff=new byte[1024];
                while ((len=is.read())!=-1){
                    baos.write(buff,0,len);
                }
                result=new String(baos.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
public class GetAsyncTaskData extends AsyncTask<String,String,String> {
    @Override
    protected String doInBackground(String... strings) {
        String result=GetNetData.getData(strings[0]);
        return result;
    }

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

猜你喜欢

转载自blog.csdn.net/qq_40441190/article/details/78534927