/
CookieList.java
71 lines (65 loc) · 2.19 KB
/
CookieList.java
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
67
68
69
70
71
package org.json;
import java.util.Iterator;
import java.text.ParseException;
/**
* Convert a web browser cookie list string to a JSONObject and back.
* <p>
* Public Domain 2002 JSON.org
* @author JSON.org
* @version 0.1
*/
public class CookieList {
private CookieList() {}
/**
* Convert a cookie list into a JSONObject. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='.
* The pairs are separated by ';'. The names and the values
* will be unescaped, possibly converting '+' and '%' sequences.
*
* To add a cookie to a cooklist,
* cookielistJSONObject.put(cookieJSONObject.getString("name"),
* cookieJSONObject.getString("value"));
* @param string A cookie list string
* @return A JSONObject
* @throws ParseException
*/
public static JSONObject toJSONObject(String string)
throws ParseException {
JSONObject o = new JSONObject();
JSONTokener x = new JSONTokener(string);
while (x.more()) {
String name = JSONTokener.unescape(x.nextTo('='));
x.next('=');
o.put(name, JSONTokener.unescape(x.nextTo(';')));
x.next();
}
return o;
}
/**
* Convert a JSONObject into a cookie list. A cookie list is a sequence
* of name/value pairs. The names are separated from the values by '='.
* The pairs are separated by ';'. The characters '%', '+', '=', and ';'
* in the names and values are replaced by "%hh".
* @param o A JSONObject
* @return A cookie list string
*/
public static String toString(JSONObject o) {
boolean b = false;
Iterator<String> keys = o.keys();
String s;
StringBuffer sb = new StringBuffer();
while (keys.hasNext()) {
s = keys.next().toString();
if (!o.isNull(s)) {
if (b) {
sb.append(';');
}
sb.append(Cookie.escape(s));
sb.append("=");
sb.append(Cookie.escape(o.getString(s)));
b = true;
}
}
return sb.toString();
}
}