wordpress放入视频链接seo关键词优化价格
实际需求:发送调用微信图片发送接口前检验图片有效性。
在 Java 中,检测图片链接是否有效可以通过发送 HTTP 请求来判断服务器返回的状态码。通过 HttpURLConnection 类,可以轻松地实现这个功能。以下是一个简单的示例代码来检测图片链接是否有效:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;public class ImageLinkChecker {public static boolean isImageLinkValid(String imageUrl) {try {// 创建 URL 对象URL url = new URL(imageUrl);// 打开与 URL 的连接HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 设置请求方法为 HEAD,不下载整个内容connection.setRequestMethod("HEAD");// 设置连接超时和读取超时connection.setConnectTimeout(5000); // 5 秒连接超时connection.setReadTimeout(5000); // 5 秒读取超时// 发起连接请求connection.connect();// 获取响应状态码int responseCode = connection.getResponseCode();// 检查响应状态码是否为 200(OK)if (responseCode == HttpURLConnection.HTTP_OK) {String contentType = connection.getContentType();// 判断返回的内容类型是否是图片格式return contentType.startsWith("image/");}} catch (IOException e) {System.out.println("Error checking image URL: " + e.getMessage());}return false; // 如果发生异常或状态码不为 200,认为链接无效}public static void main(String[] args) {String imageUrl = "https://example.com/sample-image.jpg"; // 替换为你的图片链接boolean isValid = isImageLinkValid(imageUrl);if (isValid) {System.out.println("图片链接有效");} else {System.out.println("图片链接无效");}}
}