The following is my suggestion
- public static String getInputStreamFromUrl(String remoteUrl, String chrset) {
- // TODO Auto-generated method stub
- isError = false;
- if (cacheData.containsKey(remoteUrl)) {
- Log.d(TAG, "Getting from cache file: " + remoteUrl);
- return cacheData.get(remoteUrl);
- }
- InputStream is = null;
- StringBuilder sb = new StringBuilder();
- HttpURLConnection connection;
- try {
- URL url = new URL(remoteUrl);
- Log.d(TAG, "fetch url " + remoteUrl);
- connection = (HttpURLConnection) url.openConnection();
- connection.setReadTimeout(30000);
- is = connection.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(is, chrset));
- sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line + "\n");
- }
- } catch (SocketTimeoutException e) {
- Log.e(TAG, "SocketTimeoutException" + e.getMessage());
- isError = true;
- } catch (IOException e) {
- // TODO Auto-generated catch block
- Log.e(TAG, "IOException" + e.getMessage());
- isError = true;
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- if (!sb.toString().equals("")) {
- cacheData.put(remoteUrl, sb.toString());
- }
- return sb.toString();
- }
複製代碼 |