Java从网络中获取InputStream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haoranhaoshi/article/details/84853047
                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();
                }

猜你喜欢

转载自blog.csdn.net/haoranhaoshi/article/details/84853047