I have the string below and I am trying to format it as https://any_site/any_item_picture to be able to download the image from any specific server.
output=["https://i5.walmartimages.com/asr/a4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff"
From the original variable, my code below replaces backslashes, and some other characters like "[" to URL scape codes, which I don't need. It also shows an error :
W/System.err: java.net.MalformedURLException: no protocol: ["https://i5.walmartimages.com/asr/a4ae3
The code is as follows:
@Override
public void onResponse(String output) {
String backslash = output;
String imageurl = null;
try {
imageurl = URLEncoder.encode(output, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The response after running the code:
22-10-31 15:09:20.472 10428-10428/com.example.weatherapp D/response: ["https:\/\/i5.walmartimages.com\/asr\/a4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff
Can anyone please, point in the right direction?
Thanks
CodePudding user response:
You have to extract the url first and then encode it. Encoding will not change your string. URL encoding converts characters into a format that can be transmitted over the network.
public static void main(String[] args) {
List<String> extractedUrls = extractUrls("output=[\"https://i5.walmartimages.com/asr/a4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff\"");
for (String url : extractedUrls)
{
System.out.println("url " url);
try {
System.out.println("encodedUrl " URLEncoder.encode(url, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
public static List<String> extractUrls(String text)
{
List<String> containedUrls = new ArrayList<String>();
String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\)) [\\w\\d:#@%/;$()~_?\\ -=\\\\\\.&]*)";
Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE);
Matcher urlMatcher = pattern.matcher(text);
while (urlMatcher.find())
{
containedUrls.add(text.substring(urlMatcher.start(0),
urlMatcher.end(0)));
}
return containedUrls;
}
Output:
encodedUrl https://i5.walmartimages.com/asr/a4ae31fc-572f-45a3-9d2a-4bf311b27e5d_1.ce84f66fa446e24c989f7f43f0a2a665.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff