Home | History | Annotate | Download | only in json
      1 package com.google.polo.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.Iterator;
     28 
     29 /**
     30  * Convert an HTTP header to a JSONObject and back.
     31  * @author JSON.org
     32  * @version 2008-09-18
     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     o = new JSONObject();
     73         HTTPTokener    x = new HTTPTokener(string);
     74         String         t;
     75 
     76         t = x.nextToken();
     77         if (t.toUpperCase().startsWith("HTTP")) {
     78 
     79 // Response
     80 
     81             o.put("HTTP-Version", t);
     82             o.put("Status-Code", x.nextToken());
     83             o.put("Reason-Phrase", x.nextTo('\0'));
     84             x.next();
     85 
     86         } else {
     87 
     88 // Request
     89 
     90             o.put("Method", t);
     91             o.put("Request-URI", x.nextToken());
     92             o.put("HTTP-Version", x.nextToken());
     93         }
     94 
     95 // Fields
     96 
     97         while (x.more()) {
     98             String name = x.nextTo(':');
     99             x.next(':');
    100             o.put(name, x.nextTo('\0'));
    101             x.next();
    102         }
    103         return o;
    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 o 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 o) throws JSONException {
    128         Iterator     keys = o.keys();
    129         String       s;
    130         StringBuffer sb = new StringBuffer();
    131         if (o.has("Status-Code") && o.has("Reason-Phrase")) {
    132             sb.append(o.getString("HTTP-Version"));
    133             sb.append(' ');
    134             sb.append(o.getString("Status-Code"));
    135             sb.append(' ');
    136             sb.append(o.getString("Reason-Phrase"));
    137         } else if (o.has("Method") && o.has("Request-URI")) {
    138             sb.append(o.getString("Method"));
    139             sb.append(' ');
    140             sb.append('"');
    141             sb.append(o.getString("Request-URI"));
    142             sb.append('"');
    143             sb.append(' ');
    144             sb.append(o.getString("HTTP-Version"));
    145         } else {
    146             throw new JSONException("Not enough material for an HTTP header.");
    147         }
    148         sb.append(CRLF);
    149         while (keys.hasNext()) {
    150             s = keys.next().toString();
    151             if (!s.equals("HTTP-Version")      && !s.equals("Status-Code") &&
    152                     !s.equals("Reason-Phrase") && !s.equals("Method") &&
    153                     !s.equals("Request-URI")   && !o.isNull(s)) {
    154                 sb.append(s);
    155                 sb.append(": ");
    156                 sb.append(o.getString(s));
    157                 sb.append(CRLF);
    158             }
    159         }
    160         sb.append(CRLF);
    161         return sb.toString();
    162     }
    163 }
    164