1 module hunt.httpclient.Response; 2 3 import hunt.http.client; 4 import hunt.logging.ConsoleLogger; 5 6 import std.format; 7 import std.json; 8 import std.range; 9 10 11 /** 12 * 13 */ 14 class Response { 15 private HttpClientResponse _response; 16 private string _stringContent; 17 private JSONValue _jsonContent; 18 // private string[][string] 19 20 this(HttpClientResponse response) { 21 _response = response; 22 } 23 24 /** 25 * Get the body of the response. 26 * 27 * @return string 28 */ 29 string content() { 30 if(_stringContent.empty() && _response.haveBody()) { 31 _stringContent = _response.getBody().toString(); 32 } 33 return _stringContent; 34 } 35 36 /** 37 * Get the JSON decoded body of the response as an array. 38 * 39 * @return JSONValue 40 */ 41 JSONValue json() { 42 if(_jsonContent == JSONValue.init) { 43 string content = content(); 44 _jsonContent = parseJSON(content); 45 } 46 return _jsonContent; 47 } 48 49 string opIndex(string key) { 50 string content = content(); 51 JSONValue jv; 52 try { 53 jv = parseJSON(content); 54 } catch(Exception ex) { 55 warning(ex.msg); 56 throw new Exception("The content is not a json.", ex); 57 } 58 59 auto itemPtr = key in jv; 60 if(itemPtr is null) { 61 throw new Exception(format("The key does NOT exist: %s", key)); 62 } else { 63 return jv[key].str; 64 } 65 } 66 67 string[] header(string name) { 68 HttpFields fields = _response.headers(); 69 return fields.getValuesList(name); 70 } 71 72 HttpField[] headers() { 73 HttpFields fields = _response.headers(); 74 return fields.allFields(); 75 } 76 77 /** 78 * Get the status code of the response. 79 * 80 * @return int 81 */ 82 int status() { 83 return _response.getStatus(); 84 } 85 86 /** 87 * Determine if the response code was "OK". 88 * 89 * @return bool 90 */ 91 bool isOk() { 92 return status() == 200; 93 } 94 95 /** 96 * Determine if the request was successful. 97 * 98 * @return bool 99 */ 100 bool isSuccessful() { 101 int s = status(); 102 return s >= 200 && s < 300; 103 } 104 105 /** 106 * Determine if the response was a redirect. 107 * 108 * @return bool 109 */ 110 bool isRedirect() { 111 int s = status(); 112 return s >= 300 && s < 400; 113 } 114 115 /** 116 * Determine if the response indicates a client or server error occurred. 117 * 118 * @return bool 119 */ 120 bool isFailed() { 121 return isClientError() || isServerError(); 122 } 123 124 /** 125 * Determine if the response indicates a client error occurred. 126 * 127 * @return bool 128 */ 129 bool isClientError() { 130 int s = status(); 131 return s >= 400 && s < 500; 132 } 133 134 /** 135 * Determine if the response indicates a server error occurred. 136 * 137 * @return bool 138 */ 139 bool isServerError() { 140 return status() >= 500; 141 } 142 143 Cookie[] cookies() { 144 return _response.cookies(); 145 } 146 }