Android 台灣中文網
標題:
使用httpUrlconnection遇到的問題
[打印本頁]
作者:
a1233683
時間:
2016-6-3 12:50
標題:
使用httpUrlconnection遇到的問題
各位大大 這是我的程式碼 程式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();
}
}
作者:
Leung-Jacky
時間:
2016-6-6 15:19
你沒加權限?
android.permission.INTERNET
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1