一个Android程序,大多数情况下都会涉及到与服务器的数据交换,而按谷哥官方的说法,推荐使用HttpURLConnection。
示例代码:
HttpURLConnection connection = null; String str = null; try { //TODO replace the value of url URL url = new URL(url); connection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); str = ""; String len; while ((len = br.readLine()) != null) { //while the data stream is not ended str = str + len; } } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) connection.disconnect(); } //the value of str is what you need Log.d(“data”,str);其中,url有你想要请求的网址,可以是api地址什么的
str即为最终获得的数据。
注意:该段程序并不能直接出现在UI主纯程中,这是Android API23之后的规定,耗时操作不能出现的UI主线程中。故需将它放在其它线程中,如AsyncTask中。