Java從網路中獲取InputStream
阿新 • • 發佈:2019-01-01
URL url = null; try { System.out.println(urlString); url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { InputStream inputStream = httpURLConnection.getInputStream(); // 避免請求時因網路質量導致得到的空資料 /** while(inputStream.available() == 0){ inputStream = httpURLConnection.getInputStream(); } */ /** 更新:網路阻塞時inputstream可能獲取不全,採用與httpURLConnection.getContentLength()對比的方式,得到完整inputstream */ int length = inputStream.available(); while(length != httpURLConnection.getContentLength()){ inputStream = httpURLConnection.getInputStream(); length = inputStream.available(); } } catch (IOException e) { e.printStackTrace(); }