kristofer hat die Gist bearbeitet . Zu Änderung gehen
1 file changed, 52 insertions
UrlShortener.java(Datei erstellt)
@@ -0,0 +1,52 @@ | |||
1 | + | import java.security.MessageDigest; | |
2 | + | import java.security.NoSuchAlgorithmException; | |
3 | + | import java.util.HashMap; | |
4 | + | import java.util.Map; | |
5 | + | import java.util.Random; | |
6 | + | ||
7 | + | public class UrlShortener { | |
8 | + | private Map<String, String> urlMap = new HashMap<>(); | |
9 | + | private static final String BASE_URL = "http://short.url/"; | |
10 | + | ||
11 | + | public String shortenUrl(String originalUrl) { | |
12 | + | String shortUrl = generateShortUrl(originalUrl); | |
13 | + | urlMap.put(shortUrl, originalUrl); | |
14 | + | return BASE_URL + shortUrl; | |
15 | + | } | |
16 | + | ||
17 | + | public String expandUrl(String shortUrl) { | |
18 | + | String shortKey = shortUrl.substring(BASE_URL.length()); | |
19 | + | return urlMap.get(shortKey); | |
20 | + | } | |
21 | + | ||
22 | + | private String generateShortUrl(String originalUrl) { | |
23 | + | try { | |
24 | + | MessageDigest md = MessageDigest.getInstance("MD5"); | |
25 | + | byte[] digest = md.digest(originalUrl.getBytes()); | |
26 | + | ||
27 | + | StringBuilder shortUrl = new StringBuilder(); | |
28 | + | Random random = new Random(); | |
29 | + | ||
30 | + | for (int i = 0; i < 6; i++) { | |
31 | + | int index = random.nextInt(digest.length); | |
32 | + | shortUrl.append(String.format("%02x", digest[index])); | |
33 | + | } | |
34 | + | ||
35 | + | return shortUrl.toString(); | |
36 | + | } catch (NoSuchAlgorithmException e) { | |
37 | + | e.printStackTrace(); | |
38 | + | return null; | |
39 | + | } | |
40 | + | } | |
41 | + | ||
42 | + | public static void main(String[] args) { | |
43 | + | UrlShortener urlShortener = new UrlShortener(); | |
44 | + | ||
45 | + | String longUrl = "https://www.example.com/some/long/url"; | |
46 | + | String shortUrl = urlShortener.shortenUrl(longUrl); | |
47 | + | System.out.println("Short URL: " + shortUrl); | |
48 | + | ||
49 | + | String expandedUrl = urlShortener.expandUrl(shortUrl); | |
50 | + | System.out.println("Expanded URL: " + expandedUrl); | |
51 | + | } | |
52 | + | } |
Neuer
Älter