喵喔喔
我喜欢这些:从InputStream创建Bitmap并返回它: public static Bitmap downloadImage(String url) { Bitmap bitmap = null; InputStream stream = null; BitmapFactory.Options bmOptions = new BitmapFactory.Options(); bmOptions.inSampleSize = 1; try { stream = getHttpConnection(url); bitmap = BitmapFactory.decodeStream(stream, null, bmOptions); stream.close(); } catch (IOException e1) { e1.printStackTrace(); System.out.println("downloadImage"+ e1.toString()); } return bitmap; } // Makes HttpURLConnection and returns InputStream public static InputStream getHttpConnection(String urlString) throws IOException { InputStream stream = null; URL url = new URL(urlString); URLConnection connection = url.openConnection(); try { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod("GET"); httpConnection.connect(); if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { stream = httpConnection.getInputStream(); } } catch (Exception ex) { ex.printStackTrace(); System.out.println("downloadImage" + ex.toString()); } return stream; }请记住:Android包括两个HTTP客户端:HttpURLConnection和Apache HTTP Client。 对于姜饼和后来,HttpURLConnection是最好的选择。从Android 3.x Honeycomb或更高版本,您无法在UI线程上执行网络IO并执行此操作会抛出android.os.NetworkOnMainThreadException。您必须使用Asynctask,如下所示/** AsyncTAsk for Image Bitmap */ private class AsyncGettingBitmapFromUrl extends AsyncTask { @Override protected Bitmap doInBackground(String... params) { System.out.println("doInBackground"); Bitmap bitmap = null; bitmap = AppMethods.downloadImage(params[0]); return bitmap; } @Override protected void onPostExecute(Bitmap bitmap) { System.out.println("bitmap" + bitmap); } }