首页 > 解决方案 > 休息模板从图像 URL 中检索状态代码

问题描述

我想知道图片 URL 的返回状态码,例如:

http://img.test.com/news/1439911080563855663.jpg

此 URL 可能会返回404 (NOT_FOUND)或返回实际图像JPG,在这种情况下200 (OK),我如何检查图像 url 返回的状态?

通常我们可以restTemplate用来检查休息端点的状态:

ResponseEntity<YourResponse> responseEntity =
restTemplate.getForEntity("http://your.url.here", YourResponse.class);

System.out.println(responseEntity.getStatusCode());

我们如何使用restTemplate图片网址来做到这一点?

标签: javaspring-bootresttemplate

解决方案


建立连接并获取结果代码!

URL url = null;
int code = 0 ;
        try {
            url = new URL("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png");

            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            code = connection.getResponseCode();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        System.out.println(String.valueOf(code));

推荐阅读