android工具类Z

public class Utils {
//接口回调
public interface Callback {
void onsuccess(T t);
}

//AsyncTask处理
@SuppressLint("StaticFieldLeak")
public void getResult(final String s, final Class clazz, final Callback callback) {
    new AsyncTask<String, Void, Object>() {
        @Override
        protected Object doInBackground(String... strings) {

            return getResult(strings[0], clazz);
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            callback.onsuccess(s);
        }
    }.execute(s);
}

//泛型集合
public <T> T getResult(String string, Class clazz) {
    return (T) new Gson().fromJson(getResult(string), clazz);
}

private String getResult(String string) {
    String result = "";
    try {
        URL url = new URL(string);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            result = Stream2String(connection.getInputStream());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

private String Stream2String(InputStream inputStream) throws IOException {
    StringBuilder builder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    for (String tmp = bufferedReader.readLine(); tmp != null; tmp = bufferedReader.readLine()) {
        builder.append(tmp);
    }
    return builder.toString();
}

猜你喜欢

转载自blog.csdn.net/qq_42809175/article/details/85090641
今日推荐