forked from scribejava/scribejava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathURLUtils.java
More file actions
66 lines (56 loc) · 1.77 KB
/
URLUtils.java
File metadata and controls
66 lines (56 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package org.scribe.utils;
import java.io.*;
import java.net.*;
import java.util.*;
import org.scribe.exceptions.*;
public class URLUtils
{
private static final String EMPTY_STRING = "";
private static final String UTF_8 = "UTF-8";
private static final char PAIR_SEPARATOR = '=';
private static final char PARAM_SEPARATOR = '&';
private static final String ERROR_MSG = String.format("Cannot find specified encoding: %s", UTF_8);
public static String formURLEncodeMap(Map<String, List<String>> map)
{
Preconditions.checkNotNull(map, "Cannot url-encode a null object");
return (map.size() <= 0) ? EMPTY_STRING : doFormUrlEncode(map);
}
private static String doFormUrlEncode(Map<String, List<String>> map)
{
StringBuffer encodedString = new StringBuffer();
for (String key : map.keySet())
{
for(String value: map.get(key))
{
encodedString.append(percentEncode(key)).append(PAIR_SEPARATOR).append(percentEncode(value)).append(PARAM_SEPARATOR);
}
}
return removeTrailingSeparator(encodedString);
}
private static String removeTrailingSeparator(StringBuffer buffer)
{
return buffer.toString().substring(0, buffer.length() - 1);
}
public static String percentEncode(String string)
{
Preconditions.checkNotNull(string, "Cannot encode null string");
try
{
return URLEncoder.encode(string, UTF_8);
} catch (UnsupportedEncodingException uee)
{
throw new OAuthException(ERROR_MSG, uee);
}
}
public static String percentDecode(String string)
{
Preconditions.checkNotNull(string, "Cannot decode null string");
try
{
return URLDecoder.decode(string, UTF_8);
} catch (UnsupportedEncodingException uee)
{
throw new OAuthException(ERROR_MSG, uee);
}
}
}