Java获取网络图片转化为输入流

一.通过URL获取网络图片

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
     * 获取网络图片流
     * 
     * @param url
     * @return
     */
    public InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常,图片路径为:" + url);
            e.printStackTrace();
        }
        return null;
    }

二. 注意事项

传入的URL必须是以http://开头的,因为我们使用了HttpURLConnection,示例:
这里写图片描述
https://fanyi.bdstatic.com/static/translation/img/header/logo_cbfea26.png

猜你喜欢

转载自blog.csdn.net/x541211190/article/details/80784582