84ed53baea6c092b6207883ef13e87a7925f0a73
[jalview.git] / src / org / json / HTTP.java
1 package org.json;
2
3 /*
4 Copyright (c) 2002 JSON.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 The Software shall be used for Good, not Evil.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 SOFTWARE.
25 */
26
27 import java.util.Locale;
28
29 /**
30  * Convert an HTTP header to a JSONObject and back.
31  * @author JSON.org
32  * @version 2015-12-09
33  */
34 public class HTTP {
35
36     /** Carriage return/line feed. */
37     public static final String CRLF = "\r\n";
38
39     /**
40      * Convert an HTTP header string into a JSONObject. It can be a request
41      * header or a response header. A request header will contain
42      * <pre>{
43      *    Method: "POST" (for example),
44      *    "Request-URI": "/" (for example),
45      *    "HTTP-Version": "HTTP/1.1" (for example)
46      * }</pre>
47      * A response header will contain
48      * <pre>{
49      *    "HTTP-Version": "HTTP/1.1" (for example),
50      *    "Status-Code": "200" (for example),
51      *    "Reason-Phrase": "OK" (for example)
52      * }</pre>
53      * In addition, the other parameters in the header will be captured, using
54      * the HTTP field names as JSON names, so that <pre>
55      *    Date: Sun, 26 May 2002 18:06:04 GMT
56      *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
57      *    Cache-Control: no-cache</pre>
58      * become
59      * <pre>{...
60      *    Date: "Sun, 26 May 2002 18:06:04 GMT",
61      *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
62      *    "Cache-Control": "no-cache",
63      * ...}</pre>
64      * It does no further checking or conversion. It does not parse dates.
65      * It does not do '%' transforms on URLs.
66      * @param string An HTTP header string.
67      * @return A JSONObject containing the elements and attributes
68      * of the XML string.
69      * @throws JSONException
70      */
71     public static JSONObject toJSONObject(String string) throws JSONException {
72         JSONObject     jo = new JSONObject();
73         HTTPTokener    x = new HTTPTokener(string);
74         String         token;
75
76         token = x.nextToken();
77         if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) {
78
79 // Response
80
81             jo.put("HTTP-Version", token);
82             jo.put("Status-Code", x.nextToken());
83             jo.put("Reason-Phrase", x.nextTo('\0'));
84             x.next();
85
86         } else {
87
88 // Request
89
90             jo.put("Method", token);
91             jo.put("Request-URI", x.nextToken());
92             jo.put("HTTP-Version", x.nextToken());
93         }
94
95 // Fields
96
97         while (x.more()) {
98             String name = x.nextTo(':');
99             x.next(':');
100             jo.put(name, x.nextTo('\0'));
101             x.next();
102         }
103         return jo;
104     }
105
106
107     /**
108      * Convert a JSONObject into an HTTP header. A request header must contain
109      * <pre>{
110      *    Method: "POST" (for example),
111      *    "Request-URI": "/" (for example),
112      *    "HTTP-Version": "HTTP/1.1" (for example)
113      * }</pre>
114      * A response header must contain
115      * <pre>{
116      *    "HTTP-Version": "HTTP/1.1" (for example),
117      *    "Status-Code": "200" (for example),
118      *    "Reason-Phrase": "OK" (for example)
119      * }</pre>
120      * Any other members of the JSONObject will be output as HTTP fields.
121      * The result will end with two CRLF pairs.
122      * @param jo A JSONObject
123      * @return An HTTP header string.
124      * @throws JSONException if the object does not contain enough
125      *  information.
126      */
127     public static String toString(JSONObject jo) throws JSONException {
128         StringBuilder       sb = new StringBuilder();
129         if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
130             sb.append(jo.getString("HTTP-Version"));
131             sb.append(' ');
132             sb.append(jo.getString("Status-Code"));
133             sb.append(' ');
134             sb.append(jo.getString("Reason-Phrase"));
135         } else if (jo.has("Method") && jo.has("Request-URI")) {
136             sb.append(jo.getString("Method"));
137             sb.append(' ');
138             sb.append('"');
139             sb.append(jo.getString("Request-URI"));
140             sb.append('"');
141             sb.append(' ');
142             sb.append(jo.getString("HTTP-Version"));
143         } else {
144             throw new JSONException("Not enough material for an HTTP header.");
145         }
146         sb.append(CRLF);
147         // Don't use the new entrySet API to maintain Android support
148         for (final String key : jo.keySet()) {
149             String value = jo.optString(key);
150             if (!"HTTP-Version".equals(key)      && !"Status-Code".equals(key) &&
151                     !"Reason-Phrase".equals(key) && !"Method".equals(key) &&
152                     !"Request-URI".equals(key)   && !JSONObject.NULL.equals(value)) {
153                 sb.append(key);
154                 sb.append(": ");
155                 sb.append(jo.optString(key));
156                 sb.append(CRLF);
157             }
158         }
159         sb.append(CRLF);
160         return sb.toString();
161     }
162 }