Java tutorial
//package com.java2s; /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.net.Uri; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class Main { static InputStream openContentInputStream(Context context, Uri uri) { try { return context.getContentResolver().openInputStream(uri); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } public static InputStream openInputStream(Context context, Uri uri) { if (null == uri) return null; String scheme = uri.getScheme(); InputStream stream = null; if ((scheme == null) || ("file".equals(scheme))) { stream = openFileInputStream(uri.getPath()); } else if ("content".equals(scheme)) { stream = openContentInputStream(context, uri); } else if (("http".equals(scheme)) || ("https".equals(scheme))) { stream = openRemoteInputStream(uri); } return stream; } static InputStream openFileInputStream(String path) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } static InputStream openRemoteInputStream(Uri uri) { URL finalUrl; try { finalUrl = new URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); return null; } HttpURLConnection connection; try { connection = (HttpURLConnection) finalUrl.openConnection(); } catch (IOException e) { e.printStackTrace(); return null; } connection.setInstanceFollowRedirects(false); int code; try { code = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); return null; } if ((code == 301) || (code == 302) || (code == 303)) { String newLocation = connection.getHeaderField("Location"); return openRemoteInputStream(Uri.parse(newLocation)); } try { return (InputStream) finalUrl.getContent(); } catch (IOException e) { e.printStackTrace(); } return null; } }