綁定帳號登入

Android 台灣中文網

打印 上一主題 下一主題

[求助] 使用httpUrlconnection遇到的問題

[複製連結] 查看: 1139|回覆: 1|好評: 0
跳轉到指定樓層
樓主
a1233683 | 收聽TA | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
發表於 2016-6-3 12:50

馬上加入Android 台灣中文網,立即免費下載應用遊戲。

您需要 登錄 才可以下載或查看,沒有帳號?註冊

x
各位大大 這是我的程式碼 程式Debug沒錯誤 跑模擬程式時卻開不起來 請問有人能幫幫我嘛 拜託
  • String urlString = "https://www.google.com.tw/";
  • HttpURLConnection connection = null;
  • try {
  •     // 初始化 URL
  •     URL url = new URL(urlString);
  •     // 取得連線物件
  •     connection = (HttpURLConnection) url.openConnection();
  •     // 設定 request timeout
  •     connection.setReadTimeout(1500);
  •     connection.setConnectTimeout(1500);
  •     // 模擬 Chrome 的 user agent, 因為手機的網頁內容較不完整
  •     connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36");
  •     // 設定開啟自動轉址
  •     connection.setInstanceFollowRedirects(true);
  •     // 若要求回傳 200 OK 表示成功取得網頁內容
  •     if( connection.getResponseCode() == HttpsURLConnection.HTTP_OK ){
  •         // 讀取網頁內容
  •         InputStream     inputStream     = connection.getInputStream();
  •         BufferedReader  bufferedReader  = new BufferedReader( new InputStreamReader(inputStream) );
  •         String tempStr;
  •         StringBuffer stringBuffer = new StringBuffer();
  •         while( ( tempStr = bufferedReader.readLine() ) != null ) {
  •             stringBuffer.append( tempStr );
  •         }
  •         bufferedReader.close();
  •         inputStream.close();
  •         // 取得網頁內容類型
  •         String  mime = connection.getContentType();
  •         boolean isMediaStream = false;
  •         // 判斷是否為串流檔案
  •         if( mime.indexOf("audio") == 0 ||  mime.indexOf("video") == 0 ){
  •             isMediaStream = true;
  •         }
  •         // 網頁內容字串
  •         String responseString = stringBuffer.toString();
  •     }
  • } catch (IOException e) {
  •     e.printStackTrace();
  • }
  • finally {
  •     // 中斷連線
  •     if( connection != null ) {
  •         connection.disconnect();
  •     }
  • }

「用Android 就來APK.TW」,快來加入粉絲吧!
Android 台灣中文網(APK.TW)
收藏收藏 分享分享 分享專題
用Android 就來Android 台灣中文網(https://apk.tw)
回覆

使用道具 舉報

沙發
Leung-Jacky | 收聽TA | 只看該作者
發表於 2016-6-6 15:19
你沒加權限?
android.permission.INTERNET

評分

參與人數 1碎鑽 +2 幫助 +1 收起 理由
ploglin + 2 + 1 您的用心回復提供不錯的參考價值喔!.

查看全部評分

用Android 就來Android 台灣中文網(https://apk.tw)
回覆 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則