Android - 来自URL的Imageview

时间:2013-06-22 09:57:20

标签: android url imageview

我正在尝试从以下网址下载图片。没有文件名,根据Web开发人员的说法,它正在转储二进制数据。如何获取数据并将其转换为位图并将其设置为imageview。

http://mobile.test.com/member/17/profile_picture

以下代码是我使用的代码,只有URL包含文件名。

private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("POST");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();
        }
    } catch (Exception ex) {
        throw new IOException("Error connecting");
    }
    return in;
}

private Bitmap DownloadImage(String URL) {
    Bitmap bitmap = null;
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    return bitmap;
}

0 个答案:

没有答案