2015年5月21日 星期四

【Android】HttpURLConnection Get 方法


    public static String excuteGet(String targetURL, String urlParameters) {


        URL url;
        HttpURLConnection conn = null;
        try {
            //Create connection
            url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // 進行連接,但是實際上get request要在下一句的connection.getInputStream()函數中才會真正發到伺服器
            conn.connect();

            //Get Response  ,  取得輸入流,並使用Reader讀取
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            reader.close();

            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (conn != null) {
                conn.disconnect();
            }
        }
    }

沒有留言:

張貼留言