无法从android中的HTTPS网址加载图片

时间:2014-03-15 08:24:06

标签: android

直到这个日期我的应用程序正在使用来自http网站的图像,该网站现在正在升级到https。所以问题来了,现在我的应用程序没有显示图像,即使我的网址已更新。请查看我当前的代码并帮助我。

谢谢, 瑜伽。

代码:

公共类MainActivity扩展了Activity {

public static final String URL =
    "https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg";
ImageView imageView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imageView = (ImageView) findViewById(R.id.ImageView1);

    // Create an object for subclass of AsyncTask
    GetXMLTask task = new GetXMLTask();
    // Execute the task
    task.execute(new String[] { URL });
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
        System.out.println("finished");
    }

    // Creates Bitmap from InputStream and returns it
    private 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();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpsURLConnection httpConnection = (HttpsURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

}

2 个答案:

答案 0 :(得分:0)

使用 HttpsURLConnection 代替 HttpURLConnection 进行https连接


更新:我刚检查了您图片的网址,并返回状态304,而不是200

  

请求   网址:https://googledrive.com/host/0B_DiX4MiMa3HTHdiYVRmUHBMcW8/image1.jpg   请求方法:GET状态代码:304未修改

==&GT;尝试处理状态HTTP_NOT_MODIFIED而不是HTTP_OK。或者只处理两种情况:

if (httpConnection.getResponseCode() == HttpsURLConnection.HTTP_OK ||
    httpConnection.getResponseCode() == HttpsURLConnection.HTTP_NOT_MODIFIED ) {

      stream = httpConnection.getInputStream();
} else { // just in case..
      log.wtf("Surprize!", "HTTP status was: " + httpConnection.getResponseCode());
}

请参阅有关http status 304 Not Modified的文档:

  

如果客户端执行了条件GET请求并且访问权限是   允许,但文件尚未修改,服务器应该   回复此状态代码。 304响应不得包含   message-body,因此始终由第一个空行终止   在标题字段之后。

答案 1 :(得分:0)

  {

     trustEveryone();
    // UNIVERSAL IMAGE LOADER SETUP
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc(true).cacheInMemory(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .displayer(new FadeInBitmapDisplayer(300)).build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
            getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .memoryCache(new WeakMemoryCache())
            .discCacheSize(100 * 1024 * 1024).build();

    ImageLoader.getInstance().init(config);

    //your image url
    String url = "https://thepoprewards.com.au/uploads/user_image/1514370542.jpg";

    ImageLoader imageLoader = ImageLoader.getInstance();
    DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisc(true).resetViewBeforeLoading(true)
            .build();


    imageLoader.displayImage(url, img, options);
}

编写此代码后,现在编写方法 trustEveryone

  private void trustEveryone() {
    try {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }});
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new X509TrustManager[]{new X509TrustManager(){
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {}
            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {}
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }}}, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(
                context.getSocketFactory());
    } catch (Exception e) { // should never happen
        e.printStackTrace();
    }
}