HttpURLConnection 通常在新开的一个线程内进行活动,有一个小细节需要重视,否则获不到网络数据。
new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubHttpURLConnection 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 exceptione.printStackTrace();}finally{if(connection != null){connection.disconnect();}}}}).start();
由于现在的浏览器非常智能,我们输入网址的时候不需要加前面的几个字母和符号,将这个习惯带进代码中就不行了,应该改为:
URL url = new URL("http://www.baidu.com");
这样就能获得数据了。