1. 程式人生 > >GET請求網路資料

GET請求網路資料

/**
     * 請求資料GET請求
     */
    public static String requestHttpGet(String strUrl) {

        try { //設定url
            URL url = new URL(strUrl);

            //獲取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //設定為get請求
            connection.setRequestMethod("GET");
            //設定連線主機超時時間
            connection.setConnectTimeout(5000);
            //設定從主機讀取資料超時
            connection.setReadTimeout(5000);
            //獲取請求碼(來判斷網路請求是否正確)
            int code = connection.getResponseCode();
            //判斷請求是否成功
            if (code == HttpURLConnection.HTTP_OK) {
                //如果資料請求成功
                //就獲取資料
                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
                //拼接字串
                StringBuilder builder = new StringBuilder();
                //把資料讀取從成字串
                String str = "";
                while ((str = reader.readLine()) != null) {
                    //把一行行資料拼接成一行資料
                    builder.append(str);
                }
                //返回拼接後的資料
                return builder.toString();

            }
            //關閉連線
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }