如何将返回字符串格式化为有效图片URL?Java编码报错求助
问题背景
获取到的原始字符串:
output=["https://i5.walmartimages.com/asr/a4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff"
需要提取出https://any_site/any_item_picture格式的有效图片URL,但现有代码将无关字符(如[、引号)转成URL编码,还抛出错误:
W/System.err: java.net.MalformedURLException: no protocol: ["https://i5.walmartimages.com/asr/a4ae3
现有代码
@Override public void onResponse(String output) { String backslash = output; String imageurl = null; try { imageurl = URLEncoder.encode(output, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
运行后响应
22-10-31 15:09:20.472 10428-10428/com.example.weatherapp D/response: %5B%22https%3A%5C%2F%5C%2Fi5.walmartimages.com%5C%2Fasr%5C%2Fa4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg%3FodnHeight%3D450%26odnWidth%3D450%26odnBg%3Dffffff
解决方案
核心问题是误用了URLEncoder.encode()——这个方法用于编码URL的参数部分,而非提取或清理完整URL。正确做法是先从原始字符串中剥离无效字符,提取有效URL:
示例代码
@Override public void onResponse(String output) { String imageUrl = null; // 正则匹配提取http/https开头的有效URL Pattern pattern = Pattern.compile("https?://[^\\s\\[\"]+"); Matcher matcher = pattern.matcher(output); if (matcher.find()) { imageUrl = matcher.group(); // 移除转义用的反斜杠 imageUrl = imageUrl.replace("\\", ""); // 验证并使用URL try { URL validUrl = new URL(imageUrl); // 后续下载逻辑可在此实现 } catch (MalformedURLException e) { e.printStackTrace(); } } }
逻辑说明
- 正则提取:
https?://[^\\s\\[\"]+匹配以http://或https://开头,直到遇到空格、[或"的字符串,精准定位有效URL部分。 - 清理转义符:原始字符串中的
\是转义标记,实际URL不需要,需替换移除。 - 格式验证:用
URL类初始化验证,确保最终字符串是标准可访问的URL,避免抛出MalformedURLException。
内容的提问来源于stack exchange,提问作者hbtousa

