1. 程式人生 > >網路請求工具類

網路請求工具類

public class HttpUtils {
    public static String getStringFromHttp(String urlString) {
        String result = "";

        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.setConnectTimeout(5000);

            connection.connect();

            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                result = getStringFromInputStream(is);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private static String getStringFromInputStream(InputStream is) {
        String result = "";

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int length = -1;
            byte[] buffer = new byte[1024];
            while ((length = is.read(buffer, 0, buffer.length)) != -1) {
                baos.write(buffer, 0, length);
                baos.flush();
            }

            result = baos.toString();
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;

    }
}