使用 HttpURLConnection 獲取不到網絡數據

HttpURLConnection 通常在新開的一個線程內進行活動,有一個小細節需要重視,否則獲不到網絡數據。

new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpURLConnection connection = null;
				try {
					URL url = new URL("www.baidu.com");//注意這裏
					connection = (HttpURLConnection)url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in = connection.getInputStream();
					BufferedReader reader = new BufferedReader(new InputStreamReader(in));
					StringBuilder response = new StringBuilder();
					String line;
					while((line = reader.readLine()) != null){
						response.append(line);
					}
					Message message = new Message();
					message.what = SHOW_RESPONSE;
					message.obj = response.toString();
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}finally{
					if(connection != null){
						connection.disconnect();
					}
				}
			}
		}).start();

由於現在的瀏覽器非常智能,我們輸入網址的時候不需要加前面的幾個字母和符號,將這個習慣帶進代碼中就不行了,應該改爲:

URL url = new URL("http://www.baidu.com");
這樣就能獲得數據了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章