├── .gitignore ├── Qcloud_CDN_API ├── go │ ├── README.md │ ├── qcloudcdn_api │ │ └── qcloudcdn_api.go │ └── qcloudcdn_api_demo.go ├── java │ └── cdn_openapi_demo │ │ └── src │ │ ├── Json │ │ ├── JSONArray.java │ │ ├── JSONException.java │ │ ├── JSONObject.java │ │ ├── JSONString.java │ │ ├── JSONStringer.java │ │ ├── JSONTokener.java │ │ └── JSONWriter.java │ │ ├── README.md │ │ ├── Utilities │ │ ├── Base64.java │ │ ├── MD5.java │ │ ├── Request.java │ │ ├── SHA1.java │ │ └── Sign.java │ │ └── cdnapi_demo.java ├── nodejs │ ├── README.md │ ├── index.js │ ├── libs │ │ └── utils.js │ └── package.json ├── php │ ├── AddCdnHost.php │ ├── DeleteCdnHost.php │ ├── DescribeCdnHostDetailedInfo.php │ ├── DescribeCdnHostInfo.php │ ├── DescribeCdnHosts.php │ ├── GetCdnRefreshLog.php │ ├── GetCdnStatTop.php │ ├── GetCdnStatusCode.php │ ├── GetHostInfoByHosts.php │ ├── GetHostInfoByIds.php │ ├── OfflineHost.php │ ├── OnlineHost.php │ ├── RefreshCdnDir.php │ ├── RefreshCdnUrl.php │ ├── UpdateCache.php │ ├── UpdateCdnConfig.php │ ├── UpdateCdnHost.php │ └── UpdateCdnProject.php └── python │ ├── QcloudCdnTools_V2.py │ └── README.md └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .git 3 | .DS_Store -------------------------------------------------------------------------------- /Qcloud_CDN_API/go/README.md: -------------------------------------------------------------------------------- 1 | ## qcloud cdn openapi go版本sdk 2 | 3 | ## 使用方法 4 | - 在GOPATH下的src 下添加openapi的sdk qcloudcdn_api 5 | - qcloudcdn_api.Signature 生成签名 qcloudcdn_api.SendRequest 发送请求 6 | 7 | ## 代码示例 8 | ``` 9 | package main 10 | 11 | import ( 12 | "fmt" 13 | cdnapi "qcloudcdn_api" 14 | ) 15 | 16 | func main() { 17 | /**get SecretKey & SecretId from https://console.qcloud.com/capi**/ 18 | var Requesturl string = "cdn.api.qcloud.com/v2/index.php" 19 | var SecretKey string = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 20 | var Method string = "POST" 21 | 22 | /**params to signature**/ 23 | params := make(map[string]interface{}) 24 | params["SecretId"] = "ooooooooooooooooooooooooooooooo" 25 | params["Action"] = "DescribeCdnHosts" 26 | 27 | /*use qcloudcdn_api.Signature to obtain signature and params with correct signature**/ 28 | request, _ := cdnapi.Signature(SecretKey, params, Method, Requesturl) 29 | fmt.Println("request : ", request) 30 | 31 | /*use qcloudcdn_api.SendRequest to send request**/ 32 | response := cdnapi.SendRequest(Requesturl, request, Method) 33 | fmt.Println(response) 34 | } 35 | ``` 36 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/go/qcloudcdn_api/qcloudcdn_api.go: -------------------------------------------------------------------------------- 1 | package qcloudcdn_api 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha1" 6 | "crypto/tls" 7 | "encoding/base64" 8 | "fmt" 9 | "io/ioutil" 10 | "math/rand" 11 | "net/http" 12 | "net/url" 13 | "sort" 14 | "strconv" 15 | "strings" 16 | "time" 17 | ) 18 | 19 | /*** 20 | qcloud cdn openapi 21 | author:evincai@tencent.com 22 | ***/ 23 | 24 | /** 25 | *@brief qcloud cdn openapi signature 26 | *@param secretKey secretKey to log in qcloud 27 | *@param params params of qcloud openapi interface 28 | *@param method http method 29 | *@param requesturl url 30 | 31 | *@return Signature signature 32 | *@return params params of qcloud openapi interfac include Signature 33 | **/ 34 | 35 | func Signature(secretKey string, params map[string]interface{}, method string, requesturl string) (string, map[string]interface{}) { 36 | /*add common params*/ 37 | timestamp := time.Now().Unix() 38 | rd := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(1000) 39 | params["Timestamp"] = timestamp 40 | params["Nonce"] = rd 41 | /**sort all the params to make signPlainText**/ 42 | sigUrl := method + requesturl + "?" 43 | sigParam := "" 44 | var keys []string 45 | for k := range params { 46 | keys = append(keys, k) 47 | } 48 | sort.Strings(keys) 49 | isfirst := true 50 | for _, key := range keys { 51 | if !isfirst { 52 | sigUrl = sigUrl + "&" 53 | sigParam = sigParam + "&" 54 | } 55 | isfirst = false 56 | if strings.Contains(key, "_") { 57 | strings.Replace(key, ".", "_", -1) 58 | } 59 | value := typeSwitcher(params[key]) 60 | sigUrl = sigUrl + key + "=" + value 61 | sigParam = sigParam + key + "=" + value 62 | } 63 | fmt.Println("signPlainText: ", sigUrl) 64 | unencode_sign, _sign := sign(sigUrl, secretKey) 65 | sigParam = "Signature=" + _sign + "&" + sigParam 66 | params["Signature"] = unencode_sign 67 | return sigParam, params 68 | } 69 | 70 | /** 71 | *@brief send request to qcloud 72 | *@param params params of qcloud openapi interface include signature 73 | *@param method http method 74 | *@param requesturl url 75 | 76 | *@return Signature signature 77 | *@return params params of qcloud openapi interfac include Signature 78 | **/ 79 | 80 | func SendRequest(requesturl string, params string, method string) string { 81 | requesturl = "https://" + requesturl 82 | var response string 83 | if method == "GET" { 84 | params_str := "?" + params 85 | requesturl = requesturl + params_str 86 | response = httpGet(requesturl) 87 | } else if method == "POST" { 88 | res, err := httpPost(requesturl, params) 89 | if err != nil { 90 | println(err.Error()) 91 | return err.Error() 92 | } 93 | response = string(res) 94 | } else { 95 | fmt.Println("unsuppported http method") 96 | return "unsuppported http method" 97 | } 98 | return response 99 | } 100 | 101 | func typeSwitcher(t interface{}) string { 102 | switch v := t.(type) { 103 | case int: 104 | return strconv.Itoa(v) 105 | case string: 106 | return v 107 | case int64: 108 | return strconv.Itoa(int(v)) 109 | default: 110 | return "" 111 | } 112 | } 113 | 114 | func sign(signPlainText string, secretKey string) (string, string) { 115 | key := []byte(secretKey) 116 | hash := hmac.New(sha1.New, key) 117 | hash.Write([]byte(signPlainText)) 118 | sig := base64.StdEncoding.EncodeToString([]byte(string(hash.Sum(nil)))) 119 | encd_sig := url.QueryEscape(sig) 120 | return sig, encd_sig 121 | } 122 | 123 | func httpGet(url string) string { 124 | tr := &http.Transport{ 125 | TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, 126 | } 127 | client := &http.Client{Transport: tr, Timeout: time.Duration(3) * time.Second} 128 | fmt.Println(url) 129 | resp, err := client.Get(url) 130 | if err != nil { 131 | fmt.Println(err) 132 | return err.Error() 133 | } 134 | defer resp.Body.Close() 135 | body, erro := ioutil.ReadAll(resp.Body) 136 | if erro != nil { 137 | fmt.Println("http wrong erro") 138 | return erro.Error() 139 | } 140 | return string(body) 141 | } 142 | 143 | func httpPost(requesturl string, params string) ([]byte, error) { 144 | client := &http.Client{} 145 | 146 | req, err := http.NewRequest("POST", requesturl, strings.NewReader(params)) 147 | if err != nil { 148 | return nil, err 149 | } 150 | 151 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") 152 | 153 | resp, err := client.Do(req) 154 | 155 | defer resp.Body.Close() 156 | 157 | body, err := ioutil.ReadAll(resp.Body) 158 | if err != nil { 159 | return nil, err 160 | } 161 | return body, nil 162 | } 163 | 164 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/go/qcloudcdn_api_demo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | cdnapi "qcloudcdn_api" 6 | ) 7 | 8 | func main() { 9 | /**get SecretKey & SecretId from https://console.qcloud.com/capi**/ 10 | var Requesturl string = "cdn.api.qcloud.com/v2/index.php" 11 | var SecretKey string = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 12 | var Method string = "POST" 13 | 14 | /**params to signature**/ 15 | params := make(map[string]interface{}) 16 | params["SecretId"] = "ooooooooooooooooooooooooooooooo" 17 | params["Action"] = "DescribeCdnHosts" 18 | 19 | /*use qcloudcdn_api.Signature to obtain signature and params with correct signature**/ 20 | request, _ := cdnapi.Signature(SecretKey, params, Method, Requesturl) 21 | fmt.Println("request : ", request) 22 | 23 | /*use qcloudcdn_api.SendRequest to send request**/ 24 | response := cdnapi.SendRequest(Requesturl, request, Method) 25 | fmt.Println(response) 26 | } 27 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONArray.java: -------------------------------------------------------------------------------- 1 | package 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.io.IOException; 28 | import java.io.StringWriter; 29 | import java.io.Writer; 30 | import java.lang.reflect.Array; 31 | import java.util.ArrayList; 32 | import java.util.Collection; 33 | import java.util.Iterator; 34 | import java.util.Map; 35 | 36 | /** 37 | * A JSONArray is an ordered sequence of values. Its external text form is a 38 | * string wrapped in square brackets with commas separating the values. The 39 | * internal form is an object having get and opt 40 | * methods for accessing the values by index, and put methods for 41 | * adding or replacing values. The values can be any of these types: 42 | * Boolean, JSONArray, JSONObject, 43 | * Number, String, or the 44 | * JSONObject.NULL object. 45 | *

46 | * The constructor can convert a JSON text into a Java object. The 47 | * toString method converts to JSON text. 48 | *

49 | * A get method returns a value if one can be found, and throws an 50 | * exception if one cannot be found. An opt method returns a 51 | * default value instead of throwing an exception, and so is useful for 52 | * obtaining optional values. 53 | *

54 | * The generic get() and opt() methods return an 55 | * object which you can cast or query for type. There are also typed 56 | * get and opt methods that do type checking and type 57 | * coercion for you. 58 | *

59 | * The texts produced by the toString methods strictly conform to 60 | * JSON syntax rules. The constructors are more forgiving in the texts they will 61 | * accept: 62 | *

76 | * 77 | * @author JSON.org 78 | * @version 2014-05-03 79 | */ 80 | public class JSONArray { 81 | 82 | /** 83 | * The arrayList where the JSONArray's properties are kept. 84 | */ 85 | private final ArrayList myArrayList; 86 | 87 | /** 88 | * Construct an empty JSONArray. 89 | */ 90 | public JSONArray() { 91 | this.myArrayList = new ArrayList(); 92 | } 93 | 94 | /** 95 | * Construct a JSONArray from a JSONTokener. 96 | * 97 | * @param x 98 | * A JSONTokener 99 | * @throws JSONException 100 | * If there is a syntax error. 101 | */ 102 | public JSONArray(JSONTokener x) throws JSONException { 103 | this(); 104 | if (x.nextClean() != '[') { 105 | throw x.syntaxError("A JSONArray text must start with '['"); 106 | } 107 | if (x.nextClean() != ']') { 108 | x.back(); 109 | for (;;) { 110 | if (x.nextClean() == ',') { 111 | x.back(); 112 | this.myArrayList.add(JSONObject.NULL); 113 | } else { 114 | x.back(); 115 | this.myArrayList.add(x.nextValue()); 116 | } 117 | switch (x.nextClean()) { 118 | case ',': 119 | if (x.nextClean() == ']') { 120 | return; 121 | } 122 | x.back(); 123 | break; 124 | case ']': 125 | return; 126 | default: 127 | throw x.syntaxError("Expected a ',' or ']'"); 128 | } 129 | } 130 | } 131 | } 132 | 133 | /** 134 | * Construct a JSONArray from a source JSON text. 135 | * 136 | * @param source 137 | * A string that begins with [ (left 138 | * bracket) and ends with ] 139 | *  (right bracket). 140 | * @throws JSONException 141 | * If there is a syntax error. 142 | */ 143 | public JSONArray(String source) throws JSONException { 144 | this(new JSONTokener(source)); 145 | } 146 | 147 | /** 148 | * Construct a JSONArray from a Collection. 149 | * 150 | * @param collection 151 | * A Collection. 152 | */ 153 | public JSONArray(Collection collection) { 154 | this.myArrayList = new ArrayList(); 155 | if (collection != null) { 156 | Iterator iter = collection.iterator(); 157 | while (iter.hasNext()) { 158 | this.myArrayList.add(JSONObject.wrap(iter.next())); 159 | } 160 | } 161 | } 162 | 163 | /** 164 | * Construct a JSONArray from an array 165 | * 166 | * @throws JSONException 167 | * If not an array. 168 | */ 169 | public JSONArray(Object array) throws JSONException { 170 | this(); 171 | if (array.getClass().isArray()) { 172 | int length = Array.getLength(array); 173 | for (int i = 0; i < length; i += 1) { 174 | this.put(JSONObject.wrap(Array.get(array, i))); 175 | } 176 | } else { 177 | throw new JSONException( 178 | "JSONArray initial value should be a string or collection or array."); 179 | } 180 | } 181 | 182 | /** 183 | * Get the object value associated with an index. 184 | * 185 | * @param index 186 | * The index must be between 0 and length() - 1. 187 | * @return An object value. 188 | * @throws JSONException 189 | * If there is no value for the index. 190 | */ 191 | public Object get(int index) throws JSONException { 192 | Object object = this.opt(index); 193 | if (object == null) { 194 | throw new JSONException("JSONArray[" + index + "] not found."); 195 | } 196 | return object; 197 | } 198 | 199 | /** 200 | * Get the boolean value associated with an index. The string values "true" 201 | * and "false" are converted to boolean. 202 | * 203 | * @param index 204 | * The index must be between 0 and length() - 1. 205 | * @return The truth. 206 | * @throws JSONException 207 | * If there is no value for the index or if the value is not 208 | * convertible to boolean. 209 | */ 210 | public boolean getBoolean(int index) throws JSONException { 211 | Object object = this.get(index); 212 | if (object.equals(Boolean.FALSE) 213 | || (object instanceof String && ((String) object) 214 | .equalsIgnoreCase("false"))) { 215 | return false; 216 | } else if (object.equals(Boolean.TRUE) 217 | || (object instanceof String && ((String) object) 218 | .equalsIgnoreCase("true"))) { 219 | return true; 220 | } 221 | throw new JSONException("JSONArray[" + index + "] is not a boolean."); 222 | } 223 | 224 | /** 225 | * Get the double value associated with an index. 226 | * 227 | * @param index 228 | * The index must be between 0 and length() - 1. 229 | * @return The value. 230 | * @throws JSONException 231 | * If the key is not found or if the value cannot be converted 232 | * to a number. 233 | */ 234 | public double getDouble(int index) throws JSONException { 235 | Object object = this.get(index); 236 | try { 237 | return object instanceof Number ? ((Number) object).doubleValue() 238 | : Double.parseDouble((String) object); 239 | } catch (Exception e) { 240 | throw new JSONException("JSONArray[" + index + "] is not a number."); 241 | } 242 | } 243 | 244 | /** 245 | * Get the int value associated with an index. 246 | * 247 | * @param index 248 | * The index must be between 0 and length() - 1. 249 | * @return The value. 250 | * @throws JSONException 251 | * If the key is not found or if the value is not a number. 252 | */ 253 | public int getInt(int index) throws JSONException { 254 | Object object = this.get(index); 255 | try { 256 | return object instanceof Number ? ((Number) object).intValue() 257 | : Integer.parseInt((String) object); 258 | } catch (Exception e) { 259 | throw new JSONException("JSONArray[" + index + "] is not a number."); 260 | } 261 | } 262 | 263 | /** 264 | * Get the JSONArray associated with an index. 265 | * 266 | * @param index 267 | * The index must be between 0 and length() - 1. 268 | * @return A JSONArray value. 269 | * @throws JSONException 270 | * If there is no value for the index. or if the value is not a 271 | * JSONArray 272 | */ 273 | public JSONArray getJSONArray(int index) throws JSONException { 274 | Object object = this.get(index); 275 | if (object instanceof JSONArray) { 276 | return (JSONArray) object; 277 | } 278 | throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); 279 | } 280 | 281 | /** 282 | * Get the JSONObject associated with an index. 283 | * 284 | * @param index 285 | * subscript 286 | * @return A JSONObject value. 287 | * @throws JSONException 288 | * If there is no value for the index or if the value is not a 289 | * JSONObject 290 | */ 291 | public JSONObject getJSONObject(int index) throws JSONException { 292 | Object object = this.get(index); 293 | if (object instanceof JSONObject) { 294 | return (JSONObject) object; 295 | } 296 | throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); 297 | } 298 | 299 | /** 300 | * Get the long value associated with an index. 301 | * 302 | * @param index 303 | * The index must be between 0 and length() - 1. 304 | * @return The value. 305 | * @throws JSONException 306 | * If the key is not found or if the value cannot be converted 307 | * to a number. 308 | */ 309 | public long getLong(int index) throws JSONException { 310 | Object object = this.get(index); 311 | try { 312 | return object instanceof Number ? ((Number) object).longValue() 313 | : Long.parseLong((String) object); 314 | } catch (Exception e) { 315 | throw new JSONException("JSONArray[" + index + "] is not a number."); 316 | } 317 | } 318 | 319 | /** 320 | * Get the string associated with an index. 321 | * 322 | * @param index 323 | * The index must be between 0 and length() - 1. 324 | * @return A string value. 325 | * @throws JSONException 326 | * If there is no string value for the index. 327 | */ 328 | public String getString(int index) throws JSONException { 329 | Object object = this.get(index); 330 | if (object instanceof String) { 331 | return (String) object; 332 | } 333 | throw new JSONException("JSONArray[" + index + "] not a string."); 334 | } 335 | 336 | /** 337 | * Determine if the value is null. 338 | * 339 | * @param index 340 | * The index must be between 0 and length() - 1. 341 | * @return true if the value at the index is null, or if there is no value. 342 | */ 343 | public boolean isNull(int index) { 344 | return JSONObject.NULL.equals(this.opt(index)); 345 | } 346 | 347 | /** 348 | * Make a string from the contents of this JSONArray. The 349 | * separator string is inserted between each element. Warning: 350 | * This method assumes that the data structure is acyclical. 351 | * 352 | * @param separator 353 | * A string that will be inserted between the elements. 354 | * @return a string. 355 | * @throws JSONException 356 | * If the array contains an invalid number. 357 | */ 358 | public String join(String separator) throws JSONException { 359 | int len = this.length(); 360 | StringBuilder sb = new StringBuilder(); 361 | 362 | for (int i = 0; i < len; i += 1) { 363 | if (i > 0) { 364 | sb.append(separator); 365 | } 366 | sb.append(JSONObject.valueToString(this.myArrayList.get(i))); 367 | } 368 | return sb.toString(); 369 | } 370 | 371 | /** 372 | * Get the number of elements in the JSONArray, included nulls. 373 | * 374 | * @return The length (or size). 375 | */ 376 | public int length() { 377 | return this.myArrayList.size(); 378 | } 379 | 380 | /** 381 | * Get the optional object value associated with an index. 382 | * 383 | * @param index 384 | * The index must be between 0 and length() - 1. 385 | * @return An object value, or null if there is no object at that index. 386 | */ 387 | public Object opt(int index) { 388 | return (index < 0 || index >= this.length()) ? null : this.myArrayList 389 | .get(index); 390 | } 391 | 392 | /** 393 | * Get the optional boolean value associated with an index. It returns false 394 | * if there is no value at that index, or if the value is not Boolean.TRUE 395 | * or the String "true". 396 | * 397 | * @param index 398 | * The index must be between 0 and length() - 1. 399 | * @return The truth. 400 | */ 401 | public boolean optBoolean(int index) { 402 | return this.optBoolean(index, false); 403 | } 404 | 405 | /** 406 | * Get the optional boolean value associated with an index. It returns the 407 | * defaultValue if there is no value at that index or if it is not a Boolean 408 | * or the String "true" or "false" (case insensitive). 409 | * 410 | * @param index 411 | * The index must be between 0 and length() - 1. 412 | * @param defaultValue 413 | * A boolean default. 414 | * @return The truth. 415 | */ 416 | public boolean optBoolean(int index, boolean defaultValue) { 417 | try { 418 | return this.getBoolean(index); 419 | } catch (Exception e) { 420 | return defaultValue; 421 | } 422 | } 423 | 424 | /** 425 | * Get the optional double value associated with an index. NaN is returned 426 | * if there is no value for the index, or if the value is not a number and 427 | * cannot be converted to a number. 428 | * 429 | * @param index 430 | * The index must be between 0 and length() - 1. 431 | * @return The value. 432 | */ 433 | public double optDouble(int index) { 434 | return this.optDouble(index, Double.NaN); 435 | } 436 | 437 | /** 438 | * Get the optional double value associated with an index. The defaultValue 439 | * is returned if there is no value for the index, or if the value is not a 440 | * number and cannot be converted to a number. 441 | * 442 | * @param index 443 | * subscript 444 | * @param defaultValue 445 | * The default value. 446 | * @return The value. 447 | */ 448 | public double optDouble(int index, double defaultValue) { 449 | try { 450 | return this.getDouble(index); 451 | } catch (Exception e) { 452 | return defaultValue; 453 | } 454 | } 455 | 456 | /** 457 | * Get the optional int value associated with an index. Zero is returned if 458 | * there is no value for the index, or if the value is not a number and 459 | * cannot be converted to a number. 460 | * 461 | * @param index 462 | * The index must be between 0 and length() - 1. 463 | * @return The value. 464 | */ 465 | public int optInt(int index) { 466 | return this.optInt(index, 0); 467 | } 468 | 469 | /** 470 | * Get the optional int value associated with an index. The defaultValue is 471 | * returned if there is no value for the index, or if the value is not a 472 | * number and cannot be converted to a number. 473 | * 474 | * @param index 475 | * The index must be between 0 and length() - 1. 476 | * @param defaultValue 477 | * The default value. 478 | * @return The value. 479 | */ 480 | public int optInt(int index, int defaultValue) { 481 | try { 482 | return this.getInt(index); 483 | } catch (Exception e) { 484 | return defaultValue; 485 | } 486 | } 487 | 488 | /** 489 | * Get the optional JSONArray associated with an index. 490 | * 491 | * @param index 492 | * subscript 493 | * @return A JSONArray value, or null if the index has no value, or if the 494 | * value is not a JSONArray. 495 | */ 496 | public JSONArray optJSONArray(int index) { 497 | Object o = this.opt(index); 498 | return o instanceof JSONArray ? (JSONArray) o : null; 499 | } 500 | 501 | /** 502 | * Get the optional JSONObject associated with an index. Null is returned if 503 | * the key is not found, or null if the index has no value, or if the value 504 | * is not a JSONObject. 505 | * 506 | * @param index 507 | * The index must be between 0 and length() - 1. 508 | * @return A JSONObject value. 509 | */ 510 | public JSONObject optJSONObject(int index) { 511 | Object o = this.opt(index); 512 | return o instanceof JSONObject ? (JSONObject) o : null; 513 | } 514 | 515 | /** 516 | * Get the optional long value associated with an index. Zero is returned if 517 | * there is no value for the index, or if the value is not a number and 518 | * cannot be converted to a number. 519 | * 520 | * @param index 521 | * The index must be between 0 and length() - 1. 522 | * @return The value. 523 | */ 524 | public long optLong(int index) { 525 | return this.optLong(index, 0); 526 | } 527 | 528 | /** 529 | * Get the optional long value associated with an index. The defaultValue is 530 | * returned if there is no value for the index, or if the value is not a 531 | * number and cannot be converted to a number. 532 | * 533 | * @param index 534 | * The index must be between 0 and length() - 1. 535 | * @param defaultValue 536 | * The default value. 537 | * @return The value. 538 | */ 539 | public long optLong(int index, long defaultValue) { 540 | try { 541 | return this.getLong(index); 542 | } catch (Exception e) { 543 | return defaultValue; 544 | } 545 | } 546 | 547 | /** 548 | * Get the optional string value associated with an index. It returns an 549 | * empty string if there is no value at that index. If the value is not a 550 | * string and is not null, then it is coverted to a string. 551 | * 552 | * @param index 553 | * The index must be between 0 and length() - 1. 554 | * @return A String value. 555 | */ 556 | public String optString(int index) { 557 | return this.optString(index, ""); 558 | } 559 | 560 | /** 561 | * Get the optional string associated with an index. The defaultValue is 562 | * returned if the key is not found. 563 | * 564 | * @param index 565 | * The index must be between 0 and length() - 1. 566 | * @param defaultValue 567 | * The default value. 568 | * @return A String value. 569 | */ 570 | public String optString(int index, String defaultValue) { 571 | Object object = this.opt(index); 572 | return JSONObject.NULL.equals(object) ? defaultValue : object 573 | .toString(); 574 | } 575 | 576 | /** 577 | * Append a boolean value. This increases the array's length by one. 578 | * 579 | * @param value 580 | * A boolean value. 581 | * @return this. 582 | */ 583 | public JSONArray put(boolean value) { 584 | this.put(value ? Boolean.TRUE : Boolean.FALSE); 585 | return this; 586 | } 587 | 588 | /** 589 | * Put a value in the JSONArray, where the value will be a JSONArray which 590 | * is produced from a Collection. 591 | * 592 | * @param value 593 | * A Collection value. 594 | * @return this. 595 | */ 596 | public JSONArray put(Collection value) { 597 | this.put(new JSONArray(value)); 598 | return this; 599 | } 600 | 601 | /** 602 | * Append a double value. This increases the array's length by one. 603 | * 604 | * @param value 605 | * A double value. 606 | * @throws JSONException 607 | * if the value is not finite. 608 | * @return this. 609 | */ 610 | public JSONArray put(double value) throws JSONException { 611 | Double d = new Double(value); 612 | JSONObject.testValidity(d); 613 | this.put(d); 614 | return this; 615 | } 616 | 617 | /** 618 | * Append an int value. This increases the array's length by one. 619 | * 620 | * @param value 621 | * An int value. 622 | * @return this. 623 | */ 624 | public JSONArray put(int value) { 625 | this.put(new Integer(value)); 626 | return this; 627 | } 628 | 629 | /** 630 | * Append an long value. This increases the array's length by one. 631 | * 632 | * @param value 633 | * A long value. 634 | * @return this. 635 | */ 636 | public JSONArray put(long value) { 637 | this.put(new Long(value)); 638 | return this; 639 | } 640 | 641 | /** 642 | * Put a value in the JSONArray, where the value will be a JSONObject which 643 | * is produced from a Map. 644 | * 645 | * @param value 646 | * A Map value. 647 | * @return this. 648 | */ 649 | public JSONArray put(Map value) { 650 | this.put(new JSONObject(value)); 651 | return this; 652 | } 653 | 654 | /** 655 | * Append an object value. This increases the array's length by one. 656 | * 657 | * @param value 658 | * An object value. The value should be a Boolean, Double, 659 | * Integer, JSONArray, JSONObject, Long, or String, or the 660 | * JSONObject.NULL object. 661 | * @return this. 662 | */ 663 | public JSONArray put(Object value) { 664 | this.myArrayList.add(value); 665 | return this; 666 | } 667 | 668 | /** 669 | * Put or replace a boolean value in the JSONArray. If the index is greater 670 | * than the length of the JSONArray, then null elements will be added as 671 | * necessary to pad it out. 672 | * 673 | * @param index 674 | * The subscript. 675 | * @param value 676 | * A boolean value. 677 | * @return this. 678 | * @throws JSONException 679 | * If the index is negative. 680 | */ 681 | public JSONArray put(int index, boolean value) throws JSONException { 682 | this.put(index, value ? Boolean.TRUE : Boolean.FALSE); 683 | return this; 684 | } 685 | 686 | /** 687 | * Put a value in the JSONArray, where the value will be a JSONArray which 688 | * is produced from a Collection. 689 | * 690 | * @param index 691 | * The subscript. 692 | * @param value 693 | * A Collection value. 694 | * @return this. 695 | * @throws JSONException 696 | * If the index is negative or if the value is not finite. 697 | */ 698 | public JSONArray put(int index, Collection value) throws JSONException { 699 | this.put(index, new JSONArray(value)); 700 | return this; 701 | } 702 | 703 | /** 704 | * Put or replace a double value. If the index is greater than the length of 705 | * the JSONArray, then null elements will be added as necessary to pad it 706 | * out. 707 | * 708 | * @param index 709 | * The subscript. 710 | * @param value 711 | * A double value. 712 | * @return this. 713 | * @throws JSONException 714 | * If the index is negative or if the value is not finite. 715 | */ 716 | public JSONArray put(int index, double value) throws JSONException { 717 | this.put(index, new Double(value)); 718 | return this; 719 | } 720 | 721 | /** 722 | * Put or replace an int value. If the index is greater than the length of 723 | * the JSONArray, then null elements will be added as necessary to pad it 724 | * out. 725 | * 726 | * @param index 727 | * The subscript. 728 | * @param value 729 | * An int value. 730 | * @return this. 731 | * @throws JSONException 732 | * If the index is negative. 733 | */ 734 | public JSONArray put(int index, int value) throws JSONException { 735 | this.put(index, new Integer(value)); 736 | return this; 737 | } 738 | 739 | /** 740 | * Put or replace a long value. If the index is greater than the length of 741 | * the JSONArray, then null elements will be added as necessary to pad it 742 | * out. 743 | * 744 | * @param index 745 | * The subscript. 746 | * @param value 747 | * A long value. 748 | * @return this. 749 | * @throws JSONException 750 | * If the index is negative. 751 | */ 752 | public JSONArray put(int index, long value) throws JSONException { 753 | this.put(index, new Long(value)); 754 | return this; 755 | } 756 | 757 | /** 758 | * Put a value in the JSONArray, where the value will be a JSONObject that 759 | * is produced from a Map. 760 | * 761 | * @param index 762 | * The subscript. 763 | * @param value 764 | * The Map value. 765 | * @return this. 766 | * @throws JSONException 767 | * If the index is negative or if the the value is an invalid 768 | * number. 769 | */ 770 | public JSONArray put(int index, Map value) throws JSONException { 771 | this.put(index, new JSONObject(value)); 772 | return this; 773 | } 774 | 775 | /** 776 | * Put or replace an object value in the JSONArray. If the index is greater 777 | * than the length of the JSONArray, then null elements will be added as 778 | * necessary to pad it out. 779 | * 780 | * @param index 781 | * The subscript. 782 | * @param value 783 | * The value to put into the array. The value should be a 784 | * Boolean, Double, Integer, JSONArray, JSONObject, Long, or 785 | * String, or the JSONObject.NULL object. 786 | * @return this. 787 | * @throws JSONException 788 | * If the index is negative or if the the value is an invalid 789 | * number. 790 | */ 791 | public JSONArray put(int index, Object value) throws JSONException { 792 | JSONObject.testValidity(value); 793 | if (index < 0) { 794 | throw new JSONException("JSONArray[" + index + "] not found."); 795 | } 796 | if (index < this.length()) { 797 | this.myArrayList.set(index, value); 798 | } else { 799 | while (index != this.length()) { 800 | this.put(JSONObject.NULL); 801 | } 802 | this.put(value); 803 | } 804 | return this; 805 | } 806 | 807 | /** 808 | * Remove an index and close the hole. 809 | * 810 | * @param index 811 | * The index of the element to be removed. 812 | * @return The value that was associated with the index, or null if there 813 | * was no value. 814 | */ 815 | public Object remove(int index) { 816 | return index >= 0 && index < this.length() 817 | ? this.myArrayList.remove(index) 818 | : null; 819 | } 820 | 821 | /** 822 | * Determine if two JSONArrays are similar. 823 | * They must contain similar sequences. 824 | * 825 | * @param other The other JSONArray 826 | * @return true if they are equal 827 | */ 828 | public boolean similar(Object other) { 829 | if (!(other instanceof JSONArray)) { 830 | return false; 831 | } 832 | int len = this.length(); 833 | if (len != ((JSONArray)other).length()) { 834 | return false; 835 | } 836 | for (int i = 0; i < len; i += 1) { 837 | Object valueThis = this.get(i); 838 | Object valueOther = ((JSONArray)other).get(i); 839 | if (valueThis instanceof JSONObject) { 840 | if (!((JSONObject)valueThis).similar(valueOther)) { 841 | return false; 842 | } 843 | } else if (valueThis instanceof JSONArray) { 844 | if (!((JSONArray)valueThis).similar(valueOther)) { 845 | return false; 846 | } 847 | } else if (!valueThis.equals(valueOther)) { 848 | return false; 849 | } 850 | } 851 | return true; 852 | } 853 | 854 | /** 855 | * Produce a JSONObject by combining a JSONArray of names with the values of 856 | * this JSONArray. 857 | * 858 | * @param names 859 | * A JSONArray containing a list of key strings. These will be 860 | * paired with the values. 861 | * @return A JSONObject, or null if there are no names or if this JSONArray 862 | * has no values. 863 | * @throws JSONException 864 | * If any of the names are null. 865 | */ 866 | public JSONObject toJSONObject(JSONArray names) throws JSONException { 867 | if (names == null || names.length() == 0 || this.length() == 0) { 868 | return null; 869 | } 870 | JSONObject jo = new JSONObject(); 871 | for (int i = 0; i < names.length(); i += 1) { 872 | jo.put(names.getString(i), this.opt(i)); 873 | } 874 | return jo; 875 | } 876 | 877 | /** 878 | * Make a JSON text of this JSONArray. For compactness, no unnecessary 879 | * whitespace is added. If it is not possible to produce a syntactically 880 | * correct JSON text then null will be returned instead. This could occur if 881 | * the array contains an invalid number. 882 | *

883 | * Warning: This method assumes that the data structure is acyclical. 884 | * 885 | * @return a printable, displayable, transmittable representation of the 886 | * array. 887 | */ 888 | public String toString() { 889 | try { 890 | return this.toString(0); 891 | } catch (Exception e) { 892 | return null; 893 | } 894 | } 895 | 896 | /** 897 | * Make a prettyprinted JSON text of this JSONArray. Warning: This method 898 | * assumes that the data structure is acyclical. 899 | * 900 | * @param indentFactor 901 | * The number of spaces to add to each level of indentation. 902 | * @return a printable, displayable, transmittable representation of the 903 | * object, beginning with [ (left 904 | * bracket) and ending with ] 905 | *  (right bracket). 906 | * @throws JSONException 907 | */ 908 | public String toString(int indentFactor) throws JSONException { 909 | StringWriter sw = new StringWriter(); 910 | synchronized (sw.getBuffer()) { 911 | return this.write(sw, indentFactor, 0).toString(); 912 | } 913 | } 914 | 915 | /** 916 | * Write the contents of the JSONArray as JSON text to a writer. For 917 | * compactness, no whitespace is added. 918 | *

919 | * Warning: This method assumes that the data structure is acyclical. 920 | * 921 | * @return The writer. 922 | * @throws JSONException 923 | */ 924 | public Writer write(Writer writer) throws JSONException { 925 | return this.write(writer, 0, 0); 926 | } 927 | 928 | /** 929 | * Write the contents of the JSONArray as JSON text to a writer. For 930 | * compactness, no whitespace is added. 931 | *

932 | * Warning: This method assumes that the data structure is acyclical. 933 | * 934 | * @param indentFactor 935 | * The number of spaces to add to each level of indentation. 936 | * @param indent 937 | * The indention of the top level. 938 | * @return The writer. 939 | * @throws JSONException 940 | */ 941 | Writer write(Writer writer, int indentFactor, int indent) 942 | throws JSONException { 943 | try { 944 | boolean commanate = false; 945 | int length = this.length(); 946 | writer.write('['); 947 | 948 | if (length == 1) { 949 | JSONObject.writeValue(writer, this.myArrayList.get(0), 950 | indentFactor, indent); 951 | } else if (length != 0) { 952 | final int newindent = indent + indentFactor; 953 | 954 | for (int i = 0; i < length; i += 1) { 955 | if (commanate) { 956 | writer.write(','); 957 | } 958 | if (indentFactor > 0) { 959 | writer.write('\n'); 960 | } 961 | JSONObject.indent(writer, newindent); 962 | JSONObject.writeValue(writer, this.myArrayList.get(i), 963 | indentFactor, newindent); 964 | commanate = true; 965 | } 966 | if (indentFactor > 0) { 967 | writer.write('\n'); 968 | } 969 | JSONObject.indent(writer, indent); 970 | } 971 | writer.write(']'); 972 | return writer; 973 | } catch (IOException e) { 974 | throw new JSONException(e); 975 | } 976 | } 977 | } 978 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONException.java: -------------------------------------------------------------------------------- 1 | package Json; 2 | 3 | /** 4 | * The JSONException is thrown by the JSON.org classes when things are amiss. 5 | * 6 | * @author JSON.org 7 | * @version 2014-05-03 8 | */ 9 | public class JSONException extends RuntimeException { 10 | private static final long serialVersionUID = 0; 11 | private Throwable cause; 12 | 13 | /** 14 | * Constructs a JSONException with an explanatory message. 15 | * 16 | * @param message 17 | * Detail about the reason for the exception. 18 | */ 19 | public JSONException(String message) { 20 | super(message); 21 | } 22 | 23 | /** 24 | * Constructs a new JSONException with the specified cause. 25 | * @param cause The cause. 26 | */ 27 | public JSONException(Throwable cause) { 28 | super(cause.getMessage()); 29 | this.cause = cause; 30 | } 31 | 32 | /** 33 | * Returns the cause of this exception or null if the cause is nonexistent 34 | * or unknown. 35 | * 36 | * @return the cause of this exception or null if the cause is nonexistent 37 | * or unknown. 38 | */ 39 | @Override 40 | public Throwable getCause() { 41 | return this.cause; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONString.java: -------------------------------------------------------------------------------- 1 | package Json; 2 | /** 3 | * The JSONString interface allows a toJSONString() 4 | * method so that a class can change the behavior of 5 | * JSONObject.toString(), JSONArray.toString(), 6 | * and JSONWriter.value(Object). The 7 | * toJSONString method will be used instead of the default behavior 8 | * of using the Object's toString() method and quoting the result. 9 | */ 10 | public interface JSONString { 11 | /** 12 | * The toJSONString method allows a class to produce its own JSON 13 | * serialization. 14 | * 15 | * @return A strictly syntactically correct JSON text. 16 | */ 17 | public String toJSONString(); 18 | } 19 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONStringer.java: -------------------------------------------------------------------------------- 1 | package Json; 2 | 3 | /* 4 | Copyright (c) 2006 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.io.StringWriter; 28 | 29 | /** 30 | * JSONStringer provides a quick and convenient way of producing JSON text. 31 | * The texts produced strictly conform to JSON syntax rules. No whitespace is 32 | * added, so the results are ready for transmission or storage. Each instance of 33 | * JSONStringer can produce one JSON text. 34 | *

35 | * A JSONStringer instance provides a value method for appending 36 | * values to the 37 | * text, and a key 38 | * method for adding keys before values in objects. There are array 39 | * and endArray methods that make and bound array values, and 40 | * object and endObject methods which make and bound 41 | * object values. All of these methods return the JSONWriter instance, 42 | * permitting cascade style. For example,

43 |  * myString = new JSONStringer()
44 |  *     .object()
45 |  *         .key("JSON")
46 |  *         .value("Hello, World!")
47 |  *     .endObject()
48 |  *     .toString();
which produces the string
49 |  * {"JSON":"Hello, World!"}
50 | *

51 | * The first method called must be array or object. 52 | * There are no methods for adding commas or colons. JSONStringer adds them for 53 | * you. Objects and arrays can be nested up to 20 levels deep. 54 | *

55 | * This can sometimes be easier than using a JSONObject to build a string. 56 | * @author JSON.org 57 | * @version 2008-09-18 58 | */ 59 | public class JSONStringer extends JSONWriter { 60 | /** 61 | * Make a fresh JSONStringer. It can be used to build one JSON text. 62 | */ 63 | public JSONStringer() { 64 | super(new StringWriter()); 65 | } 66 | 67 | /** 68 | * Return the JSON text. This method is used to obtain the product of the 69 | * JSONStringer instance. It will return null if there was a 70 | * problem in the construction of the JSON text (such as the calls to 71 | * array were not properly balanced with calls to 72 | * endArray). 73 | * @return The JSON text. 74 | */ 75 | public String toString() { 76 | return this.mode == 'd' ? this.writer.toString() : null; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONTokener.java: -------------------------------------------------------------------------------- 1 | package Json; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.io.InputStreamReader; 7 | import java.io.Reader; 8 | import java.io.StringReader; 9 | 10 | /* 11 | Copyright (c) 2002 JSON.org 12 | 13 | Permission is hereby granted, free of charge, to any person obtaining a copy 14 | of this software and associated documentation files (the "Software"), to deal 15 | in the Software without restriction, including without limitation the rights 16 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 17 | copies of the Software, and to permit persons to whom the Software is 18 | furnished to do so, subject to the following conditions: 19 | 20 | The above copyright notice and this permission notice shall be included in all 21 | copies or substantial portions of the Software. 22 | 23 | The Software shall be used for Good, not Evil. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | */ 33 | 34 | /** 35 | * A JSONTokener takes a source string and extracts characters and tokens from 36 | * it. It is used by the JSONObject and JSONArray constructors to parse 37 | * JSON source strings. 38 | * @author JSON.org 39 | * @version 2014-05-03 40 | */ 41 | public class JSONTokener { 42 | 43 | private long character; 44 | private boolean eof; 45 | private long index; 46 | private long line; 47 | private char previous; 48 | private Reader reader; 49 | private boolean usePrevious; 50 | 51 | 52 | /** 53 | * Construct a JSONTokener from a Reader. 54 | * 55 | * @param reader A reader. 56 | */ 57 | public JSONTokener(Reader reader) { 58 | this.reader = reader.markSupported() 59 | ? reader 60 | : new BufferedReader(reader); 61 | this.eof = false; 62 | this.usePrevious = false; 63 | this.previous = 0; 64 | this.index = 0; 65 | this.character = 1; 66 | this.line = 1; 67 | } 68 | 69 | 70 | /** 71 | * Construct a JSONTokener from an InputStream. 72 | * @param inputStream The source. 73 | */ 74 | public JSONTokener(InputStream inputStream) throws JSONException { 75 | this(new InputStreamReader(inputStream)); 76 | } 77 | 78 | 79 | /** 80 | * Construct a JSONTokener from a string. 81 | * 82 | * @param s A source string. 83 | */ 84 | public JSONTokener(String s) { 85 | this(new StringReader(s)); 86 | } 87 | 88 | 89 | /** 90 | * Back up one character. This provides a sort of lookahead capability, 91 | * so that you can test for a digit or letter before attempting to parse 92 | * the next number or identifier. 93 | */ 94 | public void back() throws JSONException { 95 | if (this.usePrevious || this.index <= 0) { 96 | throw new JSONException("Stepping back two steps is not supported"); 97 | } 98 | this.index -= 1; 99 | this.character -= 1; 100 | this.usePrevious = true; 101 | this.eof = false; 102 | } 103 | 104 | 105 | /** 106 | * Get the hex value of a character (base16). 107 | * @param c A character between '0' and '9' or between 'A' and 'F' or 108 | * between 'a' and 'f'. 109 | * @return An int between 0 and 15, or -1 if c was not a hex digit. 110 | */ 111 | public static int dehexchar(char c) { 112 | if (c >= '0' && c <= '9') { 113 | return c - '0'; 114 | } 115 | if (c >= 'A' && c <= 'F') { 116 | return c - ('A' - 10); 117 | } 118 | if (c >= 'a' && c <= 'f') { 119 | return c - ('a' - 10); 120 | } 121 | return -1; 122 | } 123 | 124 | public boolean end() { 125 | return this.eof && !this.usePrevious; 126 | } 127 | 128 | 129 | /** 130 | * Determine if the source string still contains characters that next() 131 | * can consume. 132 | * @return true if not yet at the end of the source. 133 | */ 134 | public boolean more() throws JSONException { 135 | this.next(); 136 | if (this.end()) { 137 | return false; 138 | } 139 | this.back(); 140 | return true; 141 | } 142 | 143 | 144 | /** 145 | * Get the next character in the source string. 146 | * 147 | * @return The next character, or 0 if past the end of the source string. 148 | */ 149 | public char next() throws JSONException { 150 | int c; 151 | if (this.usePrevious) { 152 | this.usePrevious = false; 153 | c = this.previous; 154 | } else { 155 | try { 156 | c = this.reader.read(); 157 | } catch (IOException exception) { 158 | throw new JSONException(exception); 159 | } 160 | 161 | if (c <= 0) { // End of stream 162 | this.eof = true; 163 | c = 0; 164 | } 165 | } 166 | this.index += 1; 167 | if (this.previous == '\r') { 168 | this.line += 1; 169 | this.character = c == '\n' ? 0 : 1; 170 | } else if (c == '\n') { 171 | this.line += 1; 172 | this.character = 0; 173 | } else { 174 | this.character += 1; 175 | } 176 | this.previous = (char) c; 177 | return this.previous; 178 | } 179 | 180 | 181 | /** 182 | * Consume the next character, and check that it matches a specified 183 | * character. 184 | * @param c The character to match. 185 | * @return The character. 186 | * @throws JSONException if the character does not match. 187 | */ 188 | public char next(char c) throws JSONException { 189 | char n = this.next(); 190 | if (n != c) { 191 | throw this.syntaxError("Expected '" + c + "' and instead saw '" + 192 | n + "'"); 193 | } 194 | return n; 195 | } 196 | 197 | 198 | /** 199 | * Get the next n characters. 200 | * 201 | * @param n The number of characters to take. 202 | * @return A string of n characters. 203 | * @throws JSONException 204 | * Substring bounds error if there are not 205 | * n characters remaining in the source string. 206 | */ 207 | public String next(int n) throws JSONException { 208 | if (n == 0) { 209 | return ""; 210 | } 211 | 212 | char[] chars = new char[n]; 213 | int pos = 0; 214 | 215 | while (pos < n) { 216 | chars[pos] = this.next(); 217 | if (this.end()) { 218 | throw this.syntaxError("Substring bounds error"); 219 | } 220 | pos += 1; 221 | } 222 | return new String(chars); 223 | } 224 | 225 | 226 | /** 227 | * Get the next char in the string, skipping whitespace. 228 | * @throws JSONException 229 | * @return A character, or 0 if there are no more characters. 230 | */ 231 | public char nextClean() throws JSONException { 232 | for (;;) { 233 | char c = this.next(); 234 | if (c == 0 || c > ' ') { 235 | return c; 236 | } 237 | } 238 | } 239 | 240 | 241 | /** 242 | * Return the characters up to the next close quote character. 243 | * Backslash processing is done. The formal JSON format does not 244 | * allow strings in single quotes, but an implementation is allowed to 245 | * accept them. 246 | * @param quote The quoting character, either 247 | * " (double quote) or 248 | * ' (single quote). 249 | * @return A String. 250 | * @throws JSONException Unterminated string. 251 | */ 252 | public String nextString(char quote) throws JSONException { 253 | char c; 254 | StringBuilder sb = new StringBuilder(); 255 | for (;;) { 256 | c = this.next(); 257 | switch (c) { 258 | case 0: 259 | case '\n': 260 | case '\r': 261 | throw this.syntaxError("Unterminated string"); 262 | case '\\': 263 | c = this.next(); 264 | switch (c) { 265 | case 'b': 266 | sb.append('\b'); 267 | break; 268 | case 't': 269 | sb.append('\t'); 270 | break; 271 | case 'n': 272 | sb.append('\n'); 273 | break; 274 | case 'f': 275 | sb.append('\f'); 276 | break; 277 | case 'r': 278 | sb.append('\r'); 279 | break; 280 | case 'u': 281 | sb.append((char)Integer.parseInt(this.next(4), 16)); 282 | break; 283 | case '"': 284 | case '\'': 285 | case '\\': 286 | case '/': 287 | sb.append(c); 288 | break; 289 | default: 290 | throw this.syntaxError("Illegal escape."); 291 | } 292 | break; 293 | default: 294 | if (c == quote) { 295 | return sb.toString(); 296 | } 297 | sb.append(c); 298 | } 299 | } 300 | } 301 | 302 | 303 | /** 304 | * Get the text up but not including the specified character or the 305 | * end of line, whichever comes first. 306 | * @param delimiter A delimiter character. 307 | * @return A string. 308 | */ 309 | public String nextTo(char delimiter) throws JSONException { 310 | StringBuilder sb = new StringBuilder(); 311 | for (;;) { 312 | char c = this.next(); 313 | if (c == delimiter || c == 0 || c == '\n' || c == '\r') { 314 | if (c != 0) { 315 | this.back(); 316 | } 317 | return sb.toString().trim(); 318 | } 319 | sb.append(c); 320 | } 321 | } 322 | 323 | 324 | /** 325 | * Get the text up but not including one of the specified delimiter 326 | * characters or the end of line, whichever comes first. 327 | * @param delimiters A set of delimiter characters. 328 | * @return A string, trimmed. 329 | */ 330 | public String nextTo(String delimiters) throws JSONException { 331 | char c; 332 | StringBuilder sb = new StringBuilder(); 333 | for (;;) { 334 | c = this.next(); 335 | if (delimiters.indexOf(c) >= 0 || c == 0 || 336 | c == '\n' || c == '\r') { 337 | if (c != 0) { 338 | this.back(); 339 | } 340 | return sb.toString().trim(); 341 | } 342 | sb.append(c); 343 | } 344 | } 345 | 346 | 347 | /** 348 | * Get the next value. The value can be a Boolean, Double, Integer, 349 | * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. 350 | * @throws JSONException If syntax error. 351 | * 352 | * @return An object. 353 | */ 354 | public Object nextValue() throws JSONException { 355 | char c = this.nextClean(); 356 | String string; 357 | 358 | switch (c) { 359 | case '"': 360 | case '\'': 361 | return this.nextString(c); 362 | case '{': 363 | this.back(); 364 | return new JSONObject(this); 365 | case '[': 366 | this.back(); 367 | return new JSONArray(this); 368 | } 369 | 370 | /* 371 | * Handle unquoted text. This could be the values true, false, or 372 | * null, or it can be a number. An implementation (such as this one) 373 | * is allowed to also accept non-standard forms. 374 | * 375 | * Accumulate characters until we reach the end of the text or a 376 | * formatting character. 377 | */ 378 | 379 | StringBuilder sb = new StringBuilder(); 380 | while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { 381 | sb.append(c); 382 | c = this.next(); 383 | } 384 | this.back(); 385 | 386 | string = sb.toString().trim(); 387 | if ("".equals(string)) { 388 | throw this.syntaxError("Missing value"); 389 | } 390 | return JSONObject.stringToValue(string); 391 | } 392 | 393 | 394 | /** 395 | * Skip characters until the next character is the requested character. 396 | * If the requested character is not found, no characters are skipped. 397 | * @param to A character to skip to. 398 | * @return The requested character, or zero if the requested character 399 | * is not found. 400 | */ 401 | public char skipTo(char to) throws JSONException { 402 | char c; 403 | try { 404 | long startIndex = this.index; 405 | long startCharacter = this.character; 406 | long startLine = this.line; 407 | this.reader.mark(1000000); 408 | do { 409 | c = this.next(); 410 | if (c == 0) { 411 | this.reader.reset(); 412 | this.index = startIndex; 413 | this.character = startCharacter; 414 | this.line = startLine; 415 | return c; 416 | } 417 | } while (c != to); 418 | } catch (IOException exception) { 419 | throw new JSONException(exception); 420 | } 421 | this.back(); 422 | return c; 423 | } 424 | 425 | 426 | /** 427 | * Make a JSONException to signal a syntax error. 428 | * 429 | * @param message The error message. 430 | * @return A JSONException object, suitable for throwing 431 | */ 432 | public JSONException syntaxError(String message) { 433 | return new JSONException(message + this.toString()); 434 | } 435 | 436 | 437 | /** 438 | * Make a printable string of this JSONTokener. 439 | * 440 | * @return " at {index} [character {character} line {line}]" 441 | */ 442 | public String toString() { 443 | return " at " + this.index + " [character " + this.character + " line " + 444 | this.line + "]"; 445 | } 446 | } 447 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Json/JSONWriter.java: -------------------------------------------------------------------------------- 1 | package Json; 2 | 3 | import java.io.IOException; 4 | import java.io.Writer; 5 | 6 | /* 7 | Copyright (c) 2006 JSON.org 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | 19 | The Software shall be used for Good, not Evil. 20 | 21 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 22 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 23 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 24 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 25 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 26 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 27 | SOFTWARE. 28 | */ 29 | 30 | /** 31 | * JSONWriter provides a quick and convenient way of producing JSON text. 32 | * The texts produced strictly conform to JSON syntax rules. No whitespace is 33 | * added, so the results are ready for transmission or storage. Each instance of 34 | * JSONWriter can produce one JSON text. 35 | *

36 | * A JSONWriter instance provides a value method for appending 37 | * values to the 38 | * text, and a key 39 | * method for adding keys before values in objects. There are array 40 | * and endArray methods that make and bound array values, and 41 | * object and endObject methods which make and bound 42 | * object values. All of these methods return the JSONWriter instance, 43 | * permitting a cascade style. For example,

 44 |  * new JSONWriter(myWriter)
 45 |  *     .object()
 46 |  *         .key("JSON")
 47 |  *         .value("Hello, World!")
 48 |  *     .endObject();
which writes
 49 |  * {"JSON":"Hello, World!"}
50 | *

51 | * The first method called must be array or object. 52 | * There are no methods for adding commas or colons. JSONWriter adds them for 53 | * you. Objects and arrays can be nested up to 20 levels deep. 54 | *

55 | * This can sometimes be easier than using a JSONObject to build a string. 56 | * @author JSON.org 57 | * @version 2011-11-24 58 | */ 59 | public class JSONWriter { 60 | private static final int maxdepth = 200; 61 | 62 | /** 63 | * The comma flag determines if a comma should be output before the next 64 | * value. 65 | */ 66 | private boolean comma; 67 | 68 | /** 69 | * The current mode. Values: 70 | * 'a' (array), 71 | * 'd' (done), 72 | * 'i' (initial), 73 | * 'k' (key), 74 | * 'o' (object). 75 | */ 76 | protected char mode; 77 | 78 | /** 79 | * The object/array stack. 80 | */ 81 | private final JSONObject stack[]; 82 | 83 | /** 84 | * The stack top index. A value of 0 indicates that the stack is empty. 85 | */ 86 | private int top; 87 | 88 | /** 89 | * The writer that will receive the output. 90 | */ 91 | protected Writer writer; 92 | 93 | /** 94 | * Make a fresh JSONWriter. It can be used to build one JSON text. 95 | */ 96 | public JSONWriter(Writer w) { 97 | this.comma = false; 98 | this.mode = 'i'; 99 | this.stack = new JSONObject[maxdepth]; 100 | this.top = 0; 101 | this.writer = w; 102 | } 103 | 104 | /** 105 | * Append a value. 106 | * @param string A string value. 107 | * @return this 108 | * @throws JSONException If the value is out of sequence. 109 | */ 110 | private JSONWriter append(String string) throws JSONException { 111 | if (string == null) { 112 | throw new JSONException("Null pointer"); 113 | } 114 | if (this.mode == 'o' || this.mode == 'a') { 115 | try { 116 | if (this.comma && this.mode == 'a') { 117 | this.writer.write(','); 118 | } 119 | this.writer.write(string); 120 | } catch (IOException e) { 121 | throw new JSONException(e); 122 | } 123 | if (this.mode == 'o') { 124 | this.mode = 'k'; 125 | } 126 | this.comma = true; 127 | return this; 128 | } 129 | throw new JSONException("Value out of sequence."); 130 | } 131 | 132 | /** 133 | * Begin appending a new array. All values until the balancing 134 | * endArray will be appended to this array. The 135 | * endArray method must be called to mark the array's end. 136 | * @return this 137 | * @throws JSONException If the nesting is too deep, or if the object is 138 | * started in the wrong place (for example as a key or after the end of the 139 | * outermost array or object). 140 | */ 141 | public JSONWriter array() throws JSONException { 142 | if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { 143 | this.push(null); 144 | this.append("["); 145 | this.comma = false; 146 | return this; 147 | } 148 | throw new JSONException("Misplaced array."); 149 | } 150 | 151 | /** 152 | * End something. 153 | * @param mode Mode 154 | * @param c Closing character 155 | * @return this 156 | * @throws JSONException If unbalanced. 157 | */ 158 | private JSONWriter end(char mode, char c) throws JSONException { 159 | if (this.mode != mode) { 160 | throw new JSONException(mode == 'a' 161 | ? "Misplaced endArray." 162 | : "Misplaced endObject."); 163 | } 164 | this.pop(mode); 165 | try { 166 | this.writer.write(c); 167 | } catch (IOException e) { 168 | throw new JSONException(e); 169 | } 170 | this.comma = true; 171 | return this; 172 | } 173 | 174 | /** 175 | * End an array. This method most be called to balance calls to 176 | * array. 177 | * @return this 178 | * @throws JSONException If incorrectly nested. 179 | */ 180 | public JSONWriter endArray() throws JSONException { 181 | return this.end('a', ']'); 182 | } 183 | 184 | /** 185 | * End an object. This method most be called to balance calls to 186 | * object. 187 | * @return this 188 | * @throws JSONException If incorrectly nested. 189 | */ 190 | public JSONWriter endObject() throws JSONException { 191 | return this.end('k', '}'); 192 | } 193 | 194 | /** 195 | * Append a key. The key will be associated with the next value. In an 196 | * object, every value must be preceded by a key. 197 | * @param string A key string. 198 | * @return this 199 | * @throws JSONException If the key is out of place. For example, keys 200 | * do not belong in arrays or if the key is null. 201 | */ 202 | public JSONWriter key(String string) throws JSONException { 203 | if (string == null) { 204 | throw new JSONException("Null key."); 205 | } 206 | if (this.mode == 'k') { 207 | try { 208 | this.stack[this.top - 1].putOnce(string, Boolean.TRUE); 209 | if (this.comma) { 210 | this.writer.write(','); 211 | } 212 | this.writer.write(JSONObject.quote(string)); 213 | this.writer.write(':'); 214 | this.comma = false; 215 | this.mode = 'o'; 216 | return this; 217 | } catch (IOException e) { 218 | throw new JSONException(e); 219 | } 220 | } 221 | throw new JSONException("Misplaced key."); 222 | } 223 | 224 | 225 | /** 226 | * Begin appending a new object. All keys and values until the balancing 227 | * endObject will be appended to this object. The 228 | * endObject method must be called to mark the object's end. 229 | * @return this 230 | * @throws JSONException If the nesting is too deep, or if the object is 231 | * started in the wrong place (for example as a key or after the end of the 232 | * outermost array or object). 233 | */ 234 | public JSONWriter object() throws JSONException { 235 | if (this.mode == 'i') { 236 | this.mode = 'o'; 237 | } 238 | if (this.mode == 'o' || this.mode == 'a') { 239 | this.append("{"); 240 | this.push(new JSONObject()); 241 | this.comma = false; 242 | return this; 243 | } 244 | throw new JSONException("Misplaced object."); 245 | 246 | } 247 | 248 | 249 | /** 250 | * Pop an array or object scope. 251 | * @param c The scope to close. 252 | * @throws JSONException If nesting is wrong. 253 | */ 254 | private void pop(char c) throws JSONException { 255 | if (this.top <= 0) { 256 | throw new JSONException("Nesting error."); 257 | } 258 | char m = this.stack[this.top - 1] == null ? 'a' : 'k'; 259 | if (m != c) { 260 | throw new JSONException("Nesting error."); 261 | } 262 | this.top -= 1; 263 | this.mode = this.top == 0 264 | ? 'd' 265 | : this.stack[this.top - 1] == null 266 | ? 'a' 267 | : 'k'; 268 | } 269 | 270 | /** 271 | * Push an array or object scope. 272 | * @param jo The scope to open. 273 | * @throws JSONException If nesting is too deep. 274 | */ 275 | private void push(JSONObject jo) throws JSONException { 276 | if (this.top >= maxdepth) { 277 | throw new JSONException("Nesting too deep."); 278 | } 279 | this.stack[this.top] = jo; 280 | this.mode = jo == null ? 'a' : 'k'; 281 | this.top += 1; 282 | } 283 | 284 | 285 | /** 286 | * Append either the value true or the value 287 | * false. 288 | * @param b A boolean. 289 | * @return this 290 | * @throws JSONException 291 | */ 292 | public JSONWriter value(boolean b) throws JSONException { 293 | return this.append(b ? "true" : "false"); 294 | } 295 | 296 | /** 297 | * Append a double value. 298 | * @param d A double. 299 | * @return this 300 | * @throws JSONException If the number is not finite. 301 | */ 302 | public JSONWriter value(double d) throws JSONException { 303 | return this.value(new Double(d)); 304 | } 305 | 306 | /** 307 | * Append a long value. 308 | * @param l A long. 309 | * @return this 310 | * @throws JSONException 311 | */ 312 | public JSONWriter value(long l) throws JSONException { 313 | return this.append(Long.toString(l)); 314 | } 315 | 316 | 317 | /** 318 | * Append an object value. 319 | * @param object The object to append. It can be null, or a Boolean, Number, 320 | * String, JSONObject, or JSONArray, or an object that implements JSONString. 321 | * @return this 322 | * @throws JSONException If the value is out of sequence. 323 | */ 324 | public JSONWriter value(Object object) throws JSONException { 325 | return this.append(JSONObject.valueToString(object)); 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/README.md: -------------------------------------------------------------------------------- 1 | ## CDN openapi java demo 2 | - 函数入口位于cdnapi_demo.java,指定接口名,公共参数(secretKey,secretId)以及接口参数。 3 | - 签名方法和请求方法位于./Utilities/Sign.java 和 ./Utilities/Request.java。 4 | - 可通过Request.generateUrl方法校验签名及请求url。 5 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Utilities/Base64.java: -------------------------------------------------------------------------------- 1 | package Utilities; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | 5 | public class Base64 { 6 | private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 7 | 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 8 | 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 9 | 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 10 | 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', 11 | '4', '5', '6', '7', '8', '9', '+', '/' }; 12 | 13 | private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, 14 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15 | -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16 | -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 17 | 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18 | 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, 19 | -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 20 | 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, 21 | -1, -1 }; 22 | 23 | public static String encode(byte[] data) { 24 | StringBuffer sb = new StringBuffer(); 25 | int len = data.length; 26 | int i = 0; 27 | int b1, b2, b3; 28 | while (i < len) { 29 | b1 = data[i++] & 0xff; 30 | if (i == len) { 31 | sb.append(base64EncodeChars[b1 >>> 2]); 32 | sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 33 | sb.append("=="); 34 | break; 35 | } 36 | b2 = data[i++] & 0xff; 37 | if (i == len) { 38 | sb.append(base64EncodeChars[b1 >>> 2]); 39 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 40 | | ((b2 & 0xf0) >>> 4)]); 41 | sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 42 | sb.append("="); 43 | break; 44 | } 45 | b3 = data[i++] & 0xff; 46 | sb.append(base64EncodeChars[b1 >>> 2]); 47 | sb.append(base64EncodeChars[((b1 & 0x03) << 4) 48 | | ((b2 & 0xf0) >>> 4)]); 49 | sb.append(base64EncodeChars[((b2 & 0x0f) << 2) 50 | | ((b3 & 0xc0) >>> 6)]); 51 | sb.append(base64EncodeChars[b3 & 0x3f]); 52 | } 53 | return sb.toString(); 54 | } 55 | 56 | public static byte[] decode(String str) throws UnsupportedEncodingException { 57 | StringBuffer sb = new StringBuffer(); 58 | byte[] data = str.getBytes("US-ASCII"); 59 | int len = data.length; 60 | int i = 0; 61 | int b1, b2, b3, b4; 62 | while (i < len) { 63 | /* b1 */ 64 | do { 65 | b1 = base64DecodeChars[data[i++]]; 66 | } while (i < len && b1 == -1); 67 | if (b1 == -1) 68 | break; 69 | /* b2 */ 70 | do { 71 | b2 = base64DecodeChars[data[i++]]; 72 | } while (i < len && b2 == -1); 73 | if (b2 == -1) 74 | break; 75 | sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); 76 | /* b3 */ 77 | do { 78 | b3 = data[i++]; 79 | if (b3 == 61) 80 | return sb.toString().getBytes("ISO-8859-1"); 81 | b3 = base64DecodeChars[b3]; 82 | } while (i < len && b3 == -1); 83 | if (b3 == -1) 84 | break; 85 | sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); 86 | /* b4 */ 87 | do { 88 | b4 = data[i++]; 89 | if (b4 == 61) 90 | return sb.toString().getBytes("ISO-8859-1"); 91 | b4 = base64DecodeChars[b4]; 92 | } while (i < len && b4 == -1); 93 | if (b4 == -1) 94 | break; 95 | sb.append((char) (((b3 & 0x03) << 6) | b4)); 96 | } 97 | return sb.toString().getBytes("ISO-8859-1"); 98 | } 99 | } -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Utilities/MD5.java: -------------------------------------------------------------------------------- 1 | package Utilities; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.security.MessageDigest; 7 | 8 | public class MD5 { 9 | 10 | public static String stringToMD5(String str) { 11 | 12 | try { 13 | byte[] strTemp = str.getBytes(); 14 | MessageDigest mdTemp = MessageDigest.getInstance("MD5"); 15 | mdTemp.update(strTemp); 16 | return toHexString(mdTemp.digest()); 17 | } catch (Exception e) { 18 | return null; 19 | } 20 | } 21 | 22 | public static String fileNameToMD5(String fileName) { 23 | InputStream inputStream = null; 24 | try { 25 | inputStream = new FileInputStream(fileName); 26 | return streamToMD5(inputStream); 27 | } catch (Exception e) { 28 | return null; 29 | } finally { 30 | if (inputStream != null) { 31 | try { 32 | inputStream.close(); 33 | } catch (IOException e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | } 38 | } 39 | 40 | public static String streamToMD5(InputStream inputStream) { 41 | try { 42 | MessageDigest mdTemp = MessageDigest.getInstance("MD5"); 43 | byte[] buffer = new byte[1024]; 44 | int numRead = 0; 45 | while ((numRead = inputStream.read(buffer)) > 0) { 46 | mdTemp.update(buffer, 0, numRead); 47 | } 48 | return toHexString(mdTemp.digest()); 49 | } catch (Exception e) { 50 | return null; 51 | } 52 | } 53 | 54 | private static String toHexString(byte[] md) { 55 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 56 | 'a', 'b', 'c', 'd', 'e', 'f' }; 57 | int j = md.length; 58 | char str[] = new char[j * 2]; 59 | for (int i = 0; i < j; i++) { 60 | byte byte0 = md[i]; 61 | str[2 * i] = hexDigits[byte0 >>> 4 & 0xf]; 62 | str[i * 2 + 1] = hexDigits[byte0 & 0xf]; 63 | } 64 | return new String(str); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Utilities/Request.java: -------------------------------------------------------------------------------- 1 | package Utilities; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.DataInputStream; 5 | import java.io.DataOutputStream; 6 | import java.io.File; 7 | import java.io.FileInputStream; 8 | import java.io.InputStreamReader; 9 | import java.io.OutputStream; 10 | import java.io.UnsupportedEncodingException; 11 | import java.net.HttpURLConnection; 12 | import java.net.URL; 13 | import java.net.URLConnection; 14 | import java.net.URLEncoder; 15 | import java.util.Map; 16 | import java.util.Random; 17 | import java.util.TreeMap; 18 | 19 | import javax.net.ssl.HostnameVerifier; 20 | import javax.net.ssl.HttpsURLConnection; 21 | import javax.net.ssl.SSLSession; 22 | 23 | 24 | 25 | /** 26 | * @brief 请求调用类 27 | * @author robinslsun 28 | */ 29 | public class Request { 30 | protected static String requestUrl = ""; 31 | protected static String rawResponse = ""; 32 | protected static String version = "CDN_API_SDK"; 33 | protected static int timeOut = 1000;//设置连接主机的超时时间,单位:毫秒,可以根据实际需求合理更改 timeOut 的值。 34 | 35 | public static String getRequestUrl() { 36 | return requestUrl; 37 | } 38 | 39 | public static String getRawResponse() { 40 | return rawResponse; 41 | } 42 | 43 | public static String generateUrl(TreeMap params, 44 | String secretId, String secretKey, String requestMethod, 45 | String requestHost, String requestPath) { 46 | if (!params.containsKey("SecretId")) 47 | params.put("SecretId", secretId); 48 | 49 | if (!params.containsKey("Nonce")) 50 | params.put("Nonce", 51 | new Random().nextInt(java.lang.Integer.MAX_VALUE)); 52 | 53 | if (!params.containsKey("Timestamp")) 54 | params.put("Timestamp", System.currentTimeMillis() / 1000); 55 | 56 | params.put("RequestClient", version); 57 | 58 | String plainText = Sign.makeSignPlainText(params, requestMethod, 59 | requestHost, requestPath); 60 | 61 | try { 62 | params.put("Signature", Sign.sign(plainText, secretKey)); 63 | } catch (Exception e) { 64 | e.printStackTrace(); 65 | } 66 | 67 | if (params.get("Action").toString().equals("MultipartUploadVodFile")) { 68 | String url = "http://" + requestHost + requestPath; 69 | url += Sign.buildParamStr1(params,requestMethod); 70 | return url; 71 | } 72 | 73 | String url = "https://" + requestHost + requestPath; 74 | if (requestMethod.equals("GET")) { 75 | url += Sign.buildParamStr1(params,requestMethod); 76 | } 77 | 78 | return url; 79 | } 80 | 81 | public static String send(TreeMap params, String secretId, 82 | String secretKey, String requestMethod, String requestHost, 83 | String requestPath, String fileName) { 84 | if (!params.containsKey("SecretId")) 85 | params.put("SecretId", secretId); 86 | 87 | if (!params.containsKey("Nonce")) 88 | params.put("Nonce", 89 | new Random().nextInt(java.lang.Integer.MAX_VALUE)); 90 | 91 | if (!params.containsKey("Timestamp")) 92 | params.put("Timestamp", System.currentTimeMillis() / 1000); 93 | 94 | params.put("RequestClient", version); 95 | params.remove("Signature"); 96 | String plainText = Sign.makeSignPlainText(params, requestMethod, 97 | requestHost, requestPath); 98 | try { 99 | params.put("Signature", Sign.sign(plainText, secretKey)); 100 | } catch (Exception e) { 101 | e.printStackTrace(); 102 | } 103 | 104 | if (params.get("Action").toString().equals("MultipartUploadVodFile")) { 105 | String url = "http://" + requestHost + requestPath; 106 | return sendMultipartUploadVodFileRequest(url, params, 107 | requestMethod, fileName); 108 | } 109 | 110 | String url = "https://" + requestHost + requestPath; 111 | 112 | return sendRequest(url, params, requestMethod, fileName); 113 | } 114 | 115 | public static String sendRequest(String url, 116 | Map requestParams, String requestMethod, 117 | String fileName) { 118 | String result = ""; 119 | BufferedReader in = null; 120 | String paramStr = ""; 121 | 122 | for (String key : requestParams.keySet()) { 123 | if (!paramStr.isEmpty()) { 124 | paramStr += '&'; 125 | } 126 | try { 127 | paramStr += key + '=' 128 | + URLEncoder.encode(requestParams.get(key).toString(),"utf-8"); 129 | } catch (UnsupportedEncodingException e) { 130 | result = "{\"code\":-2300,\"location\":\"com.qcloud.Common.Request:129\",\"message\":\"api sdk throw exception! " 131 | + e.toString() + "\"}"; 132 | } 133 | } 134 | 135 | try { 136 | 137 | if (requestMethod.equals("GET")) { 138 | if (url.indexOf('?') > 0) { 139 | url += '&' + paramStr; 140 | } else { 141 | url += '?' + paramStr; 142 | } 143 | } 144 | requestUrl = url; 145 | String BOUNDARY = "---------------------------" 146 | + MD5.stringToMD5( 147 | String.valueOf(System.currentTimeMillis())) 148 | .substring(0, 15); 149 | URL realUrl = new URL(url); 150 | URLConnection connection = null; 151 | if (url.toLowerCase().startsWith("https")) { 152 | HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl 153 | .openConnection(); 154 | 155 | httpsConn.setHostnameVerifier(new HostnameVerifier() { 156 | public boolean verify(String hostname, SSLSession session) { 157 | return true; 158 | } 159 | }); 160 | connection = httpsConn; 161 | } else { 162 | connection = realUrl.openConnection(); 163 | } 164 | 165 | // 设置通用的请求属性 166 | connection.setRequestProperty("accept", "*/*"); 167 | connection.setRequestProperty("connection", "Keep-Alive"); 168 | connection.setRequestProperty("user-agent", 169 | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 170 | // 设置链接主机超时时间 171 | connection.setConnectTimeout(timeOut); 172 | 173 | if (requestMethod.equals("POST")) { 174 | ((HttpURLConnection) connection).setRequestMethod("POST"); 175 | // 发送POST请求必须设置如下两行 176 | connection.setDoOutput(true); 177 | connection.setDoInput(true); 178 | connection.setRequestProperty("Content-Type", 179 | "multipart/form-data; boundary=" + BOUNDARY); 180 | OutputStream out = new DataOutputStream( 181 | connection.getOutputStream()); 182 | StringBuffer strBuf = new StringBuffer(); 183 | for (String key : requestParams.keySet()) { 184 | strBuf.append("\r\n").append("--").append(BOUNDARY) 185 | .append("\r\n"); 186 | strBuf.append("Content-Disposition: form-data; name=\"" 187 | + key + "\"\r\n\r\n"); 188 | strBuf.append(requestParams.get(key)); 189 | } 190 | out.write(strBuf.toString().getBytes()); 191 | if (fileName != null) { 192 | File file = new File(fileName); 193 | String filename = file.getName(); 194 | String contentType = URLConnection.getFileNameMap() 195 | .getContentTypeFor(fileName); 196 | 197 | strBuf = new StringBuffer(); 198 | strBuf.append("\r\n").append("--").append(BOUNDARY) 199 | .append("\r\n"); 200 | strBuf.append("Content-Disposition: form-data; name=\"entityFile\"; filename=\"" 201 | + filename + "\"\r\n"); 202 | strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); 203 | 204 | out.write(strBuf.toString().getBytes()); 205 | 206 | DataInputStream ins = new DataInputStream( 207 | new FileInputStream(file)); 208 | int bytes = 0; 209 | byte[] bufferOut = new byte[1024]; 210 | while ((bytes = ins.read(bufferOut)) != -1) { 211 | out.write(bufferOut, 0, bytes); 212 | } 213 | ins.close(); 214 | } 215 | byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 216 | out.write(endData); 217 | out.flush(); 218 | out.close(); 219 | } 220 | 221 | // 建立实际的连接 222 | connection.connect(); 223 | 224 | // 定义 BufferedReader输入流来读取URL的响应 225 | in = new BufferedReader(new InputStreamReader( 226 | connection.getInputStream())); 227 | 228 | String line; 229 | while ((line = in.readLine()) != null) { 230 | result += line; 231 | } 232 | 233 | } catch (Exception e) { 234 | result = "{\"code\":-2700,\"location\":\"com.qcloud.Common.Request:225\",\"message\":\"api sdk throw exception! " 235 | + e.toString() + "\"}"; 236 | } finally { 237 | // 使用finally块来关闭输入流 238 | try { 239 | if (in != null) { 240 | in.close(); 241 | } 242 | } catch (Exception e2) { 243 | result = "{\"code\":-2800,\"location\":\"com.qcloud.Common.Request:234\",\"message\":\"api sdk throw exception! " 244 | + e2.toString() + "\"}"; 245 | } 246 | } 247 | rawResponse = result; 248 | return result; 249 | } 250 | 251 | public static String sendMultipartUploadVodFileRequest(String url, 252 | Map requestParams, String requestMethod, 253 | String fileName) { 254 | String result = ""; 255 | BufferedReader in = null; 256 | String paramStr = ""; 257 | 258 | for (String key : requestParams.keySet()) { 259 | if (!paramStr.isEmpty()) { 260 | paramStr += '&'; 261 | } 262 | try { 263 | paramStr += key + '=' 264 | + URLEncoder.encode(requestParams.get(key).toString(),"utf-8"); 265 | } catch (UnsupportedEncodingException e) { 266 | result = "{\"code\":-2400,\"location\":\"com.qcloud.Common.Request:263\",\"message\":\"api sdk throw exception! " 267 | + e.toString() + "\"}"; 268 | } 269 | } 270 | 271 | try { 272 | 273 | if (url.indexOf('?') > 0) { 274 | url += '&' + paramStr; 275 | } else { 276 | url += '?' + paramStr; 277 | } 278 | 279 | System.out.println(url); 280 | 281 | requestUrl = url; 282 | // String BOUNDARY = "---------------------------" + 283 | // MD5.stringToMD5(String.valueOf(System.currentTimeMillis())).substring(0,15); 284 | URL realUrl = new URL(url); 285 | URLConnection connection = null; 286 | if (url.toLowerCase().startsWith("https")) { 287 | HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl 288 | .openConnection(); 289 | 290 | httpsConn.setHostnameVerifier(new HostnameVerifier() { 291 | public boolean verify(String hostname, SSLSession session) { 292 | return true; 293 | } 294 | }); 295 | connection = httpsConn; 296 | } else { 297 | connection = realUrl.openConnection(); 298 | } 299 | 300 | // 设置通用的请求属性 301 | connection.setRequestProperty("accept", "*/*"); 302 | connection.setRequestProperty("connection", "Keep-Alive"); 303 | connection.setRequestProperty("user-agent", 304 | "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 305 | connection.setDoOutput(true); 306 | connection.setDoInput(true); 307 | // 设置链接主机超时时间 308 | connection.setConnectTimeout(timeOut); 309 | 310 | File file = new File(fileName); 311 | long file_length = (Long) requestParams.get("fileSize"); 312 | OutputStream out = new DataOutputStream( 313 | connection.getOutputStream()); 314 | DataInputStream ins = new DataInputStream(new FileInputStream(file)); 315 | int offset = ((Integer) requestParams.get("offset")).intValue(); 316 | int dataSize = ((Integer) requestParams.get("dataSize")).intValue(); 317 | if (offset >= file_length) { 318 | return "{\"code\":-3001,\"location\":\"com.qcloud.Common.Request:303\",\"message\":\"api sdk throw exception! offset larger than the size of file\"}"; 319 | } 320 | int skipBytes = ins.skipBytes(offset); 321 | int page = dataSize / 1024; 322 | int remainder = dataSize % 1024; 323 | int bytes = 0; 324 | byte[] bufferOut = new byte[1024]; 325 | byte[] bufferOut2 = new byte[remainder]; 326 | while (page != 0) { 327 | if ((bytes = ins.read(bufferOut)) != -1) { 328 | out.write(bufferOut, 0, bytes); 329 | } 330 | page = page - 1; 331 | } 332 | if ((bytes = ins.read(bufferOut2)) != -1) { 333 | out.write(bufferOut2, 0, bytes); 334 | } 335 | ins.close(); 336 | out.flush(); 337 | out.close(); 338 | 339 | // 建立实际的连接 340 | connection.connect(); 341 | try { 342 | // 定义 BufferedReader输入流来读取URL的响应 343 | in = new BufferedReader(new InputStreamReader( 344 | connection.getInputStream())); 345 | } catch (Exception e) { 346 | result = "{\"code\":-3002,\"location\":\"com.qcloud.Common.Request:331\",\"message\":\"api sdk throw exception! protocol doesn't support input or the character Encoding is not supported." 347 | + "details: " + e.toString() + "\"}"; 348 | if (in != null) { 349 | in.close(); 350 | } 351 | rawResponse = result; 352 | return result; 353 | } 354 | String line; 355 | while ((line = in.readLine()) != null) { 356 | result += line; 357 | } 358 | 359 | } catch (Exception e) { 360 | result = "{\"code\":-3000,\"location\":\"com.qcloud.Common.Request:345\",\"message\":\"api sdk throw exception! " 361 | + e.toString() + "\"}"; 362 | } finally { 363 | // 使用finally块来关闭输入流 364 | try { 365 | if (in != null) { 366 | in.close(); 367 | } 368 | } catch (Exception e2) { 369 | result = "{\"code\":-3003,\"location\":\"com.qcloud.Common.Request:354\",\"message\":\"api sdk throw exception! " 370 | + e2.toString() + "\"}"; 371 | } 372 | } 373 | rawResponse = result; 374 | return result; 375 | } 376 | } 377 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Utilities/SHA1.java: -------------------------------------------------------------------------------- 1 | package Utilities; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.security.MessageDigest; 7 | 8 | public class SHA1 { 9 | 10 | public static String stringToSHA(String str) { 11 | 12 | try { 13 | byte[] strTemp = str.getBytes(); 14 | MessageDigest mdTemp = MessageDigest.getInstance("SHA-1"); //SHA-256 15 | mdTemp.update(strTemp); 16 | return toHexString(mdTemp.digest()); 17 | } catch (Exception e) { 18 | return null; 19 | } 20 | } 21 | 22 | public static String fileNameToSHA(String fileName) { 23 | InputStream inputStream = null; 24 | try { 25 | inputStream = new FileInputStream(fileName); 26 | return streamToSHA(inputStream); 27 | } catch (Exception e) { 28 | return null; 29 | } finally { 30 | if (inputStream != null) { 31 | try { 32 | inputStream.close(); 33 | } catch (IOException e) { 34 | e.printStackTrace(); 35 | } 36 | } 37 | } 38 | } 39 | 40 | public static String streamToSHA(InputStream inputStream) { 41 | try { 42 | MessageDigest mdTemp = MessageDigest.getInstance("SHA-1"); //SHA-256 43 | byte[] buffer = new byte[1024]; 44 | int numRead = 0; 45 | while ((numRead = inputStream.read(buffer)) > 0) { 46 | mdTemp.update(buffer, 0, numRead); 47 | } 48 | return toHexString(mdTemp.digest()); 49 | } catch (Exception e) { 50 | return null; 51 | } 52 | } 53 | 54 | private static String toHexString(byte[] md) { 55 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 56 | 'a', 'b', 'c', 'd', 'e', 'f' }; 57 | int j = md.length; 58 | char str[] = new char[j * 2]; 59 | for (int i = 0; i < j; i++) { 60 | byte byte0 = md[i]; 61 | str[2 * i] = hexDigits[byte0 >>> 4 & 0xf]; 62 | str[i * 2 + 1] = hexDigits[byte0 & 0xf]; 63 | } 64 | return new String(str); 65 | } 66 | 67 | public static void main(String[]args) { 68 | System.out.println("start..."); 69 | System.out.println(SHA1.fileNameToSHA("d:\\test.rmvb")); 70 | System.out.println("end..."); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/Utilities/Sign.java: -------------------------------------------------------------------------------- 1 | package Utilities; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.security.InvalidKeyException; 5 | import java.security.NoSuchAlgorithmException; 6 | import java.util.TreeMap; 7 | 8 | import javax.crypto.Mac; 9 | import javax.crypto.spec.SecretKeySpec; 10 | 11 | //import sun.misc.BASE64Encoder; 12 | //import org.apache.commons.codec.binary.Base64; 13 | 14 | 15 | public class Sign { 16 | // 编码方式 17 | private static final String CONTENT_CHARSET = "UTF-8"; 18 | 19 | // HMAC算法 20 | private static final String HMAC_ALGORITHM = "HmacSHA1"; 21 | 22 | /** 23 | * @brief 签名 24 | * @author gavinyao@tencent.com 25 | * @date 2014-08-13 21:07:27 26 | * 27 | * @param signStr 被加密串 28 | * @param secret 加密密钥 29 | * 30 | * @return 31 | */ 32 | public static String sign(String signStr, String secret) 33 | throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException 34 | { 35 | 36 | String sig = null; 37 | Mac mac = Mac.getInstance(HMAC_ALGORITHM); 38 | SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac.getAlgorithm()); 39 | 40 | mac.init(secretKey); 41 | byte[] hash = mac.doFinal(signStr.getBytes(CONTENT_CHARSET)); 42 | 43 | // base64 44 | //sig = new String(new BASE64Encoder().encode(hash).getBytes()); 45 | //sig = new String(Base64.encodeBase64(hash)); 46 | sig = new String(Base64.encode(hash)); 47 | 48 | return sig; 49 | } 50 | 51 | public static String makeSignPlainText(TreeMap requestParams, String requestMethod, String requestHost, String requestPath) { 52 | 53 | String retStr = ""; 54 | retStr += requestMethod; 55 | retStr += requestHost; 56 | retStr += requestPath; 57 | retStr += buildParamStr1(requestParams, requestMethod); 58 | 59 | return retStr; 60 | } 61 | 62 | protected static String buildParamStr1(TreeMap requestParams, String requestMethod) { 63 | return buildParamStr(requestParams, requestMethod); 64 | } 65 | 66 | protected static String buildParamStr(TreeMap requestParams, String requestMethod) { 67 | 68 | String retStr = ""; 69 | for(String key: requestParams.keySet()) { 70 | //排除上传文件的参数 71 | if(requestMethod == "POST" && requestParams.get(key).toString().substring(0, 1).equals("@")){ 72 | continue; 73 | } 74 | if (retStr.length()==0) { 75 | retStr += '?'; 76 | } else { 77 | retStr += '&'; 78 | } 79 | retStr += key.replace("_", ".") + '=' + requestParams.get(key).toString(); 80 | 81 | } 82 | return retStr; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/java/cdn_openapi_demo/src/cdnapi_demo.java: -------------------------------------------------------------------------------- 1 | import java.util.TreeMap; 2 | import Json.*; 3 | import Utilities.*; 4 | 5 | 6 | public class cdnapi_demo { 7 | public static void main(String[] args) { 8 | 9 | //params 10 | String serverHost = "cdn.api.qcloud.com"; 11 | String serverUri = "/v2/index.php"; 12 | String secretId = "xxxxx"; 13 | String secretKey = "xxxxxx"; 14 | String requestMethod = "GET"; 15 | String defaultRegion = "gz"; 16 | String action="RefreshCdnUrl"; 17 | 18 | /*add interface params,e.g.DescribeHosts*/ 19 | TreeMap params = new TreeMap(); 20 | params.put("urls.0","http://xxxxxxx.com/test.php"); 21 | params.put("urls.1","http://xxxxx.com/test2.php"); 22 | if(params == null) 23 | params = new TreeMap(); 24 | action = cdnapi_demo.ucFirst(action); 25 | params.put("Action", action); 26 | System.out.println(params); 27 | try{ 28 | String response = Request.send(params, secretId, secretKey, requestMethod, serverHost, serverUri, null); 29 | /*use generateUrl to get url*/ 30 | String url = Request.generateUrl(params, secretId, secretKey, requestMethod, serverHost, serverUri); 31 | System.out.println("correct request url:["+url+"]"); 32 | JSONObject result = new JSONObject(response); 33 | System.out.println(result); 34 | } 35 | catch (Exception e){ 36 | System.out.println("error..." + e.getMessage()); 37 | } 38 | 39 | } 40 | private static String ucFirst(String word){ 41 | return word.replaceFirst(word.substring(0, 1), 42 | word.substring(0, 1).toUpperCase()); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/nodejs/README.md: -------------------------------------------------------------------------------- 1 | ## qcloud cdn openapi nodejs版本sdk 2 | 3 | ## 安装 4 | 5 | npm install qcloud-cdn-node-sdk --save 6 | 7 | ## API 8 | 9 | 参见[API文档](https://github.com/QCloudCDN/CDN_API_SDK/blob/master/README.md) 10 | 11 | 12 | ## 错误码 13 | 14 | 参见[错误码文档](https://www.qcloud.com/document/product/228/5078) 15 | 16 | ## 使用 17 | 18 | ### 准备工作 19 | 20 | qcloud账号的secret_id和secret_key可以从[https://console.qcloud.com/capi](https://console.qcloud.com/capi) 获取 21 | 22 | ### 初始化SDK配置 23 | 24 | ```js 25 | const qcloudSDK = require('qcloud-cdn-node-sdk'); 26 | 27 | qcloudSDK.config({ 28 | secretId: 'qcloud账号的secretId', 29 | secretKey: 'qcloud账号的参数表示secretKey' 30 | }) 31 | ``` 32 | 33 | ### 调用具体的CDN方法 34 | 35 | ```js 36 | /************Action对应的名字************/ 37 | 38 | //API文档见 https://github.com/QCloudCDN/CDN_API_SDK/blob/master/README.md 39 | 40 | // DescribleCdnHosts 41 | // GetHostInfoByHost 42 | // GetHostInfoById 43 | // RefreshCdnUrl 44 | // RefreshCdnDir 45 | // UpdateCache 46 | // UpdateCdnProject 47 | // UpdateCdnHost 48 | // UpdateCdnConfig 49 | // OfflineHost 50 | // AddCdnHost 51 | // OnlineHost 52 | // DeleteCdnHost 53 | // GenerateLogList 54 | // GetCdnRefreshLog 55 | // GetCdnStatTop 56 | // GetCdnStatusCode 57 | // DescribeCdnHostDetailedInfo 58 | // DescribeCdnHostInfo 59 | /************************/ 60 | 61 | // action对应的参数无需传递公共请求参数 62 | qcloudSDK.request('Action的名字', action对应的参数对象, callback) 63 | 64 | ``` 65 | 66 | ## 示例 67 | 68 | ```js 69 | const qcloudSDK = require('qcloud-cdn-node-sdk'); 70 | 71 | qcloudSDK.config({ 72 | secretId: 'AAAAAAAAAAAAAAAAA', 73 | secretKey: 'BBBBBBBBBBBBBBBBBB' 74 | }) 75 | 76 | qcloudSDK.request('DescribeCdnHostInfo', { 77 | 'startDate': '2016-12-01', 78 | 'endDate': '2016-12-01', 79 | 'statType': 'bandwidth', 80 | 'projects.0': '123', 81 | 'hosts.0': 'www.test.com', 82 | 'hosts.1': 'www.test2.com' 83 | }, (res) => { 84 | // res为json格式 85 | // do something 86 | }) 87 | ``` 88 | 89 | ## 反馈 90 | 91 | 欢迎提issue 92 | 93 | ## LICENSE 94 | 95 | MIT 96 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/nodejs/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var requestLib = require('request'); 4 | var _ = require('lodash'); 5 | var utilityLib = require('utility'); 6 | var commonUtils = require('./libs/utils'); 7 | 8 | var OPENAPI_HOST = 'cdn.api.qcloud.com'; 9 | var OPENAPI_PATH = '/v2/index.php'; 10 | var OPENAPI_URL = 'https://' + OPENAPI_HOST + OPENAPI_PATH; 11 | var METHOD = 'POST'; 12 | 13 | 14 | var QcloudSDK = function() { 15 | this.secretKey = ''; 16 | this.secretId = ''; 17 | this.token = ''; 18 | } 19 | 20 | QcloudSDK.prototype.config = function(userConfig) { 21 | checkUserConfig(userConfig) 22 | 23 | this.secretKey = userConfig.secretKey; 24 | this.secretId = userConfig.secretId; 25 | this.token = userConfig.token; 26 | } 27 | 28 | QcloudSDK.prototype.request = function(actionName, params, callback) { 29 | checkUserConfig({ 30 | secretKey: this.secretKey, 31 | secretId: this.secretId, 32 | token: this.token, 33 | }) 34 | 35 | params = params || {}; 36 | var timestamp = Math.ceil((new Date()-0)/1000); 37 | var nonce = _.random(1000000); 38 | var signature = createSignature(actionName, nonce, timestamp, params, this.secretKey, this.secretId, this.token); 39 | 40 | var requestData = _.assign({ 41 | 'Action': actionName, 42 | 'Timestamp': timestamp, 43 | 'Nonce': nonce, 44 | 'SecretId': this.secretId, 45 | 'Signature': signature, 46 | 'Token': this.token 47 | }, params) 48 | 49 | requestData = commonUtils.serialize(requestData) 50 | 51 | requestLib.post({ 52 | url: OPENAPI_URL, 53 | form: requestData 54 | }, function(err, httpRes, body) { 55 | if(err) { 56 | callback(err); 57 | return; 58 | } 59 | 60 | callback(body) 61 | }) 62 | } 63 | 64 | 65 | function checkUserConfig(userConfig) { 66 | 67 | if(!_.isPlainObject(userConfig) 68 | || !_.isString(userConfig['secretKey']) 69 | || !_.isString(userConfig['secretId'])) { 70 | throw new Error('::config function should be called required an object param which contains secretKey[String] and secretId[String]') 71 | } 72 | } 73 | 74 | function createSignature(actionName, nonce, timestamp, params, secretKey, secretId, token) { 75 | var originObject = _.assign({ 76 | 'Action': actionName, 77 | 'Nonce': nonce, 78 | 'SecretId': secretId, 79 | 'Timestamp': timestamp, 80 | 'Token': token 81 | }, params); 82 | var sortedObject = commonUtils.sortObject(originObject); 83 | var serializeString = commonUtils.serialize(sortedObject); 84 | var originSignature = METHOD+OPENAPI_HOST+OPENAPI_PATH+'?'+serializeString; 85 | var signature = encodeURIComponent(utilityLib.hmac('sha1', secretKey, originSignature)); 86 | 87 | return signature 88 | } 89 | 90 | 91 | var qcloudSDK = new QcloudSDK(); 92 | 93 | 94 | module.exports = qcloudSDK; 95 | 96 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/nodejs/libs/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var _ = require('lodash'); 4 | 5 | 6 | var sortObject = function(obj, fn) { 7 | var keys = _.sortBy(_.keys(obj), fn); 8 | var res = {}; 9 | 10 | _.forIn(keys, function(key) { 11 | res[key] = obj[key]; 12 | }) 13 | 14 | return res 15 | } 16 | 17 | var serialize = function(obj) { 18 | var res = ''; 19 | var mapValue = _.map(obj, function(value, key) { 20 | return (key+'='+value) 21 | }); 22 | 23 | res = _.join(mapValue, '&'); 24 | 25 | return res 26 | } 27 | 28 | exports.sortObject = sortObject; 29 | exports.serialize = serialize; 30 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/nodejs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "qcloud-cdn-node-sdk", 3 | "version": "1.0.0", 4 | "description": "腾讯云CDN OpenAPI Node.js SDK", 5 | "main": "index.js", 6 | "dependencies": { 7 | "lodash": "^4.17.2", 8 | "request": "^2.79.0", 9 | "utility": "^1.9.0" 10 | }, 11 | "devDependencies": { 12 | "mocha": "^3.2.0" 13 | }, 14 | "scripts": { 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/nodejs" 19 | }, 20 | "keywords": [ 21 | "qcloud", 22 | "nodejs", 23 | "sdk" 24 | ], 25 | "author": "QcloudCDN", 26 | "license": "MIT" 27 | } 28 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/AddCdnHost.php: -------------------------------------------------------------------------------- 1 | "c.u-ndefined.com", 24 | "projectId" => 0, 25 | "hostType" => "cname", 26 | "origin" => "e.u-ndefinded.com:12023" 27 | ); 28 | 29 | $HttpUrl="cdn.api.qcloud.com"; 30 | 31 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 32 | $HttpMethod="POST"; 33 | 34 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 35 | $isHttps =true; 36 | 37 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 38 | $COMMON_PARAMS = array( 39 | 'Nonce' => rand(), 40 | 'Timestamp' =>time(NULL), 41 | 'Action' =>$action, 42 | 'SecretId' => $secretId, 43 | ); 44 | 45 | /***********************************************************************************/ 46 | 47 | 48 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 49 | 50 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 51 | { 52 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 53 | 54 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 55 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 56 | ksort($ReqParaArray); 57 | 58 | /**********************************生成签名原文********************************** 59 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 60 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 61 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 62 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 63 | * ****************************************************************************/ 64 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 65 | 66 | $isFirst = true; 67 | foreach ($ReqParaArray as $key => $value) 68 | { 69 | if (!$isFirst) 70 | { 71 | $SigTxt = $SigTxt."&"; 72 | } 73 | $isFirst= false; 74 | 75 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 76 | if(strpos($key, '_')) 77 | { 78 | $key = str_replace('_', '.', $key); 79 | } 80 | 81 | $SigTxt=$SigTxt.$key."=".$value; 82 | } 83 | 84 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 85 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 86 | 87 | 88 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 89 | $Req = "Signature=".urlencode($Signature); 90 | foreach ($ReqParaArray as $key => $value) 91 | { 92 | $Req=$Req."&".$key."=".urlencode($value); 93 | } 94 | 95 | /*********************************发送请求********************************/ 96 | if($HttpMethod === 'GET') 97 | { 98 | if($isHttps === true) 99 | { 100 | $Req="https://".$FullHttpUrl."?".$Req; 101 | } 102 | else 103 | { 104 | $Req="http://".$FullHttpUrl."?".$Req; 105 | } 106 | 107 | $Rsp = file_get_contents($Req); 108 | 109 | } 110 | else 111 | { 112 | if($isHttps === true) 113 | { 114 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 115 | } 116 | else 117 | { 118 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 119 | } 120 | } 121 | 122 | var_export(json_decode($Rsp,true)); 123 | } 124 | 125 | function SendPost($FullHttpUrl, $Req, $isHttps) 126 | { 127 | 128 | $ch = curl_init(); 129 | curl_setopt($ch, CURLOPT_POST, 1); 130 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 131 | 132 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 133 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 134 | if ($isHttps === true) { 135 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 136 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 137 | } 138 | 139 | $result = curl_exec($ch); 140 | 141 | return $result; 142 | } 143 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/DeleteCdnHost.php: -------------------------------------------------------------------------------- 1 | 862, 18 | ); 19 | 20 | $HttpUrl="cdn.api.qcloud.com"; 21 | 22 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 23 | $HttpMethod="POST"; 24 | 25 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 26 | $isHttps =true; 27 | 28 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 29 | $COMMON_PARAMS = array( 30 | 'Nonce' => rand(), 31 | 'Timestamp' =>time(NULL), 32 | 'Action' =>$action, 33 | 'SecretId' => $secretId, 34 | ); 35 | 36 | /***********************************************************************************/ 37 | 38 | 39 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 40 | 41 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 42 | { 43 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 44 | 45 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 46 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 47 | ksort($ReqParaArray); 48 | 49 | /**********************************生成签名原文********************************** 50 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 51 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 52 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 53 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 54 | * ****************************************************************************/ 55 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 56 | 57 | $isFirst = true; 58 | foreach ($ReqParaArray as $key => $value) 59 | { 60 | if (!$isFirst) 61 | { 62 | $SigTxt = $SigTxt."&"; 63 | } 64 | $isFirst= false; 65 | 66 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 67 | if(strpos($key, '_')) 68 | { 69 | $key = str_replace('_', '.', $key); 70 | } 71 | 72 | $SigTxt=$SigTxt.$key."=".$value; 73 | } 74 | 75 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 76 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 77 | 78 | 79 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 80 | $Req = "Signature=".urlencode($Signature); 81 | foreach ($ReqParaArray as $key => $value) 82 | { 83 | $Req=$Req."&".$key."=".urlencode($value); 84 | } 85 | 86 | /*********************************发送请求********************************/ 87 | if($HttpMethod === 'GET') 88 | { 89 | if($isHttps === true) 90 | { 91 | $Req="https://".$FullHttpUrl."?".$Req; 92 | } 93 | else 94 | { 95 | $Req="http://".$FullHttpUrl."?".$Req; 96 | } 97 | 98 | $Rsp = file_get_contents($Req); 99 | 100 | } 101 | else 102 | { 103 | if($isHttps === true) 104 | { 105 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 106 | } 107 | else 108 | { 109 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 110 | } 111 | } 112 | 113 | var_export(json_decode($Rsp,true)); 114 | } 115 | 116 | function SendPost($FullHttpUrl, $Req, $isHttps) 117 | { 118 | 119 | $ch = curl_init(); 120 | curl_setopt($ch, CURLOPT_POST, 1); 121 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 122 | 123 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 124 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 125 | if ($isHttps === true) { 126 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 128 | } 129 | 130 | $result = curl_exec($ch); 131 | 132 | return $result; 133 | } 134 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/DescribeCdnHostDetailedInfo.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | 24 | /*****************参数************************/ 25 | /** 26 | 参数名 类型 是否必填 描述 27 | startDate string 是 开始日期 28 | endDate string 是 结束日期 29 | statType string 是 查看维度 30 | projects array 是 项目id 31 | hosts array 否 查询域名 32 | **/ 33 | 34 | 35 | $PRIVATE_PARAMS = array( 36 | 'startDate'=> '2016-04-26', 37 | 'endDate' => '2016-04-27', 38 | 'statType' => 'bandwidth', 39 | 'projects.0'=> 0, 40 | 'hosts.0' =>'ping.cdn.qcloud.com' 41 | ); 42 | 43 | 44 | /***********************************************************************************/ 45 | 46 | 47 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 48 | 49 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 50 | { 51 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 52 | 53 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 54 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 55 | ksort($ReqParaArray); 56 | 57 | /**********************************生成签名原文********************************** 58 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 59 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 60 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 61 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 62 | * ****************************************************************************/ 63 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 64 | 65 | $isFirst = true; 66 | foreach ($ReqParaArray as $key => $value) 67 | { 68 | if (!$isFirst) 69 | { 70 | $SigTxt = $SigTxt."&"; 71 | } 72 | $isFirst= false; 73 | 74 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 75 | if(strpos($key, '_')) 76 | { 77 | $key = str_replace('_', '.', $key); 78 | } 79 | 80 | $SigTxt=$SigTxt.$key."=".$value; 81 | } 82 | 83 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 84 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 85 | 86 | 87 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 88 | $Req = "Signature=".urlencode($Signature); 89 | foreach ($ReqParaArray as $key => $value) 90 | { 91 | $Req=$Req."&".$key."=".urlencode($value); 92 | } 93 | 94 | /*********************************发送请求********************************/ 95 | if($HttpMethod === 'GET') 96 | { 97 | if($isHttps === true) 98 | { 99 | $Req="https://".$FullHttpUrl."?".$Req; 100 | } 101 | else 102 | { 103 | $Req="http://".$FullHttpUrl."?".$Req; 104 | } 105 | 106 | $Rsp = file_get_contents($Req); 107 | 108 | } 109 | else 110 | { 111 | if($isHttps === true) 112 | { 113 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 114 | } 115 | else 116 | { 117 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 118 | } 119 | } 120 | 121 | var_export(json_decode($Rsp,true)); 122 | } 123 | 124 | function SendPost($FullHttpUrl, $Req, $isHttps) 125 | { 126 | 127 | $ch = curl_init(); 128 | curl_setopt($ch, CURLOPT_POST, 1); 129 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 130 | 131 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 132 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 133 | if ($isHttps === true) { 134 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 135 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 136 | } 137 | 138 | $result = curl_exec($ch); 139 | 140 | return $result; 141 | } 142 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/DescribeCdnHostInfo.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | 24 | /*****************参数************************/ 25 | /** 26 | 参数名 类型 是否必填 描述 27 | startDate string 是 开始日期 28 | endDate string 是 结束日期 29 | statType string 是 查看维度 30 | projects array 是 项目id 31 | hosts array 否 查询域名 32 | **/ 33 | 34 | 35 | $PRIVATE_PARAMS = array( 36 | 'startDate'=> '2016-04-26', 37 | 'endDate' => '2016-04-27', 38 | 'statType' => 'bandwidth', 39 | 'projects.0'=> 0, 40 | 'hosts.0' =>'ping.cdn.qcloud.com' 41 | ); 42 | 43 | 44 | /***********************************************************************************/ 45 | 46 | 47 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 48 | 49 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 50 | { 51 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 52 | 53 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 54 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 55 | ksort($ReqParaArray); 56 | 57 | /**********************************生成签名原文********************************** 58 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 59 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 60 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 61 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 62 | * ****************************************************************************/ 63 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 64 | 65 | $isFirst = true; 66 | foreach ($ReqParaArray as $key => $value) 67 | { 68 | if (!$isFirst) 69 | { 70 | $SigTxt = $SigTxt."&"; 71 | } 72 | $isFirst= false; 73 | 74 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 75 | if(strpos($key, '_')) 76 | { 77 | $key = str_replace('_', '.', $key); 78 | } 79 | 80 | $SigTxt=$SigTxt.$key."=".$value; 81 | } 82 | 83 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 84 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 85 | 86 | 87 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 88 | $Req = "Signature=".urlencode($Signature); 89 | foreach ($ReqParaArray as $key => $value) 90 | { 91 | $Req=$Req."&".$key."=".urlencode($value); 92 | } 93 | 94 | /*********************************发送请求********************************/ 95 | if($HttpMethod === 'GET') 96 | { 97 | if($isHttps === true) 98 | { 99 | $Req="https://".$FullHttpUrl."?".$Req; 100 | } 101 | else 102 | { 103 | $Req="http://".$FullHttpUrl."?".$Req; 104 | } 105 | 106 | $Rsp = file_get_contents($Req); 107 | 108 | } 109 | else 110 | { 111 | if($isHttps === true) 112 | { 113 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 114 | } 115 | else 116 | { 117 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 118 | } 119 | } 120 | 121 | var_export(json_decode($Rsp,true)); 122 | } 123 | 124 | function SendPost($FullHttpUrl, $Req, $isHttps) 125 | { 126 | 127 | $ch = curl_init(); 128 | curl_setopt($ch, CURLOPT_POST, 1); 129 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 130 | 131 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 132 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 133 | if ($isHttps === true) { 134 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 135 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 136 | } 137 | 138 | $result = curl_exec($ch); 139 | 140 | return $result; 141 | } 142 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/DescribeCdnHosts.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | $PRIVATE_PARAMS = array(); 24 | 25 | /***********************************************************************************/ 26 | 27 | 28 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 29 | 30 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 31 | { 32 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 33 | 34 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 35 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 36 | ksort($ReqParaArray); 37 | 38 | /**********************************生成签名原文********************************** 39 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 40 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 41 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 42 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 43 | * ****************************************************************************/ 44 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 45 | 46 | $isFirst = true; 47 | foreach ($ReqParaArray as $key => $value) 48 | { 49 | if (!$isFirst) 50 | { 51 | $SigTxt = $SigTxt."&"; 52 | } 53 | $isFirst= false; 54 | 55 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 56 | if(strpos($key, '_')) 57 | { 58 | $key = str_replace('_', '.', $key); 59 | } 60 | 61 | $SigTxt=$SigTxt.$key."=".$value; 62 | } 63 | 64 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 65 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 66 | 67 | 68 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 69 | $Req = "Signature=".urlencode($Signature); 70 | foreach ($ReqParaArray as $key => $value) 71 | { 72 | $Req=$Req."&".$key."=".urlencode($value); 73 | } 74 | 75 | /*********************************发送请求********************************/ 76 | if($HttpMethod === 'GET') 77 | { 78 | if($isHttps === true) 79 | { 80 | $Req="https://".$FullHttpUrl."?".$Req; 81 | } 82 | else 83 | { 84 | $Req="http://".$FullHttpUrl."?".$Req; 85 | } 86 | 87 | $Rsp = file_get_contents($Req); 88 | 89 | } 90 | else 91 | { 92 | if($isHttps === true) 93 | { 94 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 95 | } 96 | else 97 | { 98 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 99 | } 100 | } 101 | 102 | var_export(json_decode($Rsp,true)); 103 | } 104 | 105 | function SendPost($FullHttpUrl, $Req, $isHttps) 106 | { 107 | 108 | $ch = curl_init(); 109 | curl_setopt($ch, CURLOPT_POST, 1); 110 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 111 | 112 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 113 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 114 | if ($isHttps === true) { 115 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 116 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 117 | } 118 | 119 | $result = curl_exec($ch); 120 | 121 | return $result; 122 | } 123 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/GetCdnRefreshLog.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | /*****************参数************************/ 24 | /** 25 | 参数名 类型 是否必填 描述 26 | startDate string 是 开始日期 27 | endDate string 是 结束日期 28 | url string 否 查询的URL 29 | **/ 30 | 31 | 32 | $PRIVATE_PARAMS = array( 33 | 'startDate'=> '2016-04-26', 34 | 'endDate' => '2016-04-27', 35 | ); 36 | 37 | 38 | /***********************************************************************************/ 39 | 40 | 41 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 42 | 43 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 44 | { 45 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 46 | 47 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 48 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 49 | ksort($ReqParaArray); 50 | 51 | /**********************************生成签名原文********************************** 52 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 53 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 54 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 55 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 56 | * ****************************************************************************/ 57 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 58 | 59 | $isFirst = true; 60 | foreach ($ReqParaArray as $key => $value) 61 | { 62 | if (!$isFirst) 63 | { 64 | $SigTxt = $SigTxt."&"; 65 | } 66 | $isFirst= false; 67 | 68 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 69 | if(strpos($key, '_')) 70 | { 71 | $key = str_replace('_', '.', $key); 72 | } 73 | 74 | $SigTxt=$SigTxt.$key."=".$value; 75 | } 76 | 77 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 78 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 79 | 80 | 81 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 82 | $Req = "Signature=".urlencode($Signature); 83 | foreach ($ReqParaArray as $key => $value) 84 | { 85 | $Req=$Req."&".$key."=".urlencode($value); 86 | } 87 | 88 | /*********************************发送请求********************************/ 89 | if($HttpMethod === 'GET') 90 | { 91 | if($isHttps === true) 92 | { 93 | $Req="https://".$FullHttpUrl."?".$Req; 94 | } 95 | else 96 | { 97 | $Req="http://".$FullHttpUrl."?".$Req; 98 | } 99 | 100 | $Rsp = file_get_contents($Req); 101 | 102 | } 103 | else 104 | { 105 | if($isHttps === true) 106 | { 107 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 108 | } 109 | else 110 | { 111 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 112 | } 113 | } 114 | 115 | var_export(json_decode($Rsp,true)); 116 | } 117 | 118 | function SendPost($FullHttpUrl, $Req, $isHttps) 119 | { 120 | 121 | $ch = curl_init(); 122 | curl_setopt($ch, CURLOPT_POST, 1); 123 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 124 | 125 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 126 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 127 | if ($isHttps === true) { 128 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 129 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 130 | } 131 | 132 | $result = curl_exec($ch); 133 | 134 | return $result; 135 | } 136 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/GetCdnStatTop.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | 24 | /*****************参数************************/ 25 | /** 26 | 参数名 类型 是否必填 描述 27 | startDate string 是 开始日期 28 | endDate string 是 结束日期 29 | statType string 是 查看维度 30 | projects array 是 项目id 31 | hosts array 否 查询域名 32 | period int 否 数据采样间隔 33 | **/ 34 | 35 | 36 | $PRIVATE_PARAMS = array( 37 | 'startDate'=> '2016-04-26', 38 | 'endDate' => '2016-04-27', 39 | 'statType' => 'bandwidth', 40 | 'projects.0'=> 0, 41 | 'hosts.0' =>'ping.cdn.qcloud.com' 42 | ); 43 | 44 | 45 | /***********************************************************************************/ 46 | 47 | 48 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 49 | 50 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 51 | { 52 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 53 | 54 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 55 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 56 | ksort($ReqParaArray); 57 | 58 | /**********************************生成签名原文********************************** 59 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 60 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 61 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 62 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 63 | * ****************************************************************************/ 64 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 65 | 66 | $isFirst = true; 67 | foreach ($ReqParaArray as $key => $value) 68 | { 69 | if (!$isFirst) 70 | { 71 | $SigTxt = $SigTxt."&"; 72 | } 73 | $isFirst= false; 74 | 75 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 76 | if(strpos($key, '_')) 77 | { 78 | $key = str_replace('_', '.', $key); 79 | } 80 | 81 | $SigTxt=$SigTxt.$key."=".$value; 82 | } 83 | 84 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 85 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 86 | 87 | 88 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 89 | $Req = "Signature=".urlencode($Signature); 90 | foreach ($ReqParaArray as $key => $value) 91 | { 92 | $Req=$Req."&".$key."=".urlencode($value); 93 | } 94 | 95 | /*********************************发送请求********************************/ 96 | if($HttpMethod === 'GET') 97 | { 98 | if($isHttps === true) 99 | { 100 | $Req="https://".$FullHttpUrl."?".$Req; 101 | } 102 | else 103 | { 104 | $Req="http://".$FullHttpUrl."?".$Req; 105 | } 106 | 107 | $Rsp = file_get_contents($Req); 108 | 109 | } 110 | else 111 | { 112 | if($isHttps === true) 113 | { 114 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 115 | } 116 | else 117 | { 118 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 119 | } 120 | } 121 | 122 | var_export(json_decode($Rsp,true)); 123 | } 124 | 125 | function SendPost($FullHttpUrl, $Req, $isHttps) 126 | { 127 | 128 | $ch = curl_init(); 129 | curl_setopt($ch, CURLOPT_POST, 1); 130 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 131 | 132 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 133 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 134 | if ($isHttps === true) { 135 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 136 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 137 | } 138 | 139 | $result = curl_exec($ch); 140 | 141 | return $result; 142 | } 143 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/GetCdnStatusCode.php: -------------------------------------------------------------------------------- 1 | rand(), 18 | 'Timestamp' =>time(NULL), 19 | 'Action' =>$action, 20 | 'SecretId' => $secretId, 21 | ); 22 | 23 | /*****************参数************************/ 24 | /** 25 | 参数名 类型 是否必填 描述 26 | startDate string 是 开始日期 27 | endDate string 是 结束日期 28 | projects array 是 项目id 29 | hosts array 否 查询域名 30 | sources array 否 网络层级 31 | period int 否 数据采样间隔 32 | **/ 33 | 34 | 35 | $PRIVATE_PARAMS = array( 36 | 'startDate'=> '2016-04-26', 37 | 'endDate' => '2016-04-27', 38 | 'projects.0'=> 0, 39 | 'hosts.0' =>'ping.cdn.qcloud.com' 40 | ); 41 | 42 | 43 | /***********************************************************************************/ 44 | 45 | 46 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 47 | 48 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 49 | { 50 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 51 | 52 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 53 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 54 | ksort($ReqParaArray); 55 | 56 | /**********************************生成签名原文********************************** 57 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 58 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 59 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 60 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 61 | * ****************************************************************************/ 62 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 63 | 64 | $isFirst = true; 65 | foreach ($ReqParaArray as $key => $value) 66 | { 67 | if (!$isFirst) 68 | { 69 | $SigTxt = $SigTxt."&"; 70 | } 71 | $isFirst= false; 72 | 73 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 74 | if(strpos($key, '_')) 75 | { 76 | $key = str_replace('_', '.', $key); 77 | } 78 | 79 | $SigTxt=$SigTxt.$key."=".$value; 80 | } 81 | 82 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 83 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 84 | 85 | 86 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 87 | $Req = "Signature=".urlencode($Signature); 88 | foreach ($ReqParaArray as $key => $value) 89 | { 90 | $Req=$Req."&".$key."=".urlencode($value); 91 | } 92 | 93 | /*********************************发送请求********************************/ 94 | if($HttpMethod === 'GET') 95 | { 96 | if($isHttps === true) 97 | { 98 | $Req="https://".$FullHttpUrl."?".$Req; 99 | } 100 | else 101 | { 102 | $Req="http://".$FullHttpUrl."?".$Req; 103 | } 104 | 105 | $Rsp = file_get_contents($Req); 106 | 107 | } 108 | else 109 | { 110 | if($isHttps === true) 111 | { 112 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 113 | } 114 | else 115 | { 116 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 117 | } 118 | } 119 | 120 | var_export(json_decode($Rsp,true)); 121 | } 122 | 123 | function SendPost($FullHttpUrl, $Req, $isHttps) 124 | { 125 | 126 | $ch = curl_init(); 127 | curl_setopt($ch, CURLOPT_POST, 1); 128 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 129 | 130 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 131 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 132 | if ($isHttps === true) { 133 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 134 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 135 | } 136 | 137 | $result = curl_exec($ch); 138 | 139 | return $result; 140 | } 141 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/GetHostInfoByHosts.php: -------------------------------------------------------------------------------- 1 | "ping.cdn.qcloud.com", 10 | "hosts.1" => "img46.ddimg.cn", 11 | ); 12 | 13 | $HttpUrl="cdn.api.qcloud.com"; 14 | 15 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 16 | $HttpMethod="POST"; 17 | 18 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 19 | $isHttps =true; 20 | 21 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 22 | $COMMON_PARAMS = array( 23 | 'Nonce' => rand(), 24 | 'Timestamp' =>time(NULL), 25 | 'Action' =>$action, 26 | 'SecretId' => $secretId, 27 | ); 28 | 29 | /***********************************************************************************/ 30 | 31 | 32 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 33 | 34 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 35 | { 36 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 37 | 38 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 39 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 40 | ksort($ReqParaArray); 41 | 42 | /**********************************生成签名原文********************************** 43 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 44 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 45 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 46 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 47 | * ****************************************************************************/ 48 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 49 | 50 | $isFirst = true; 51 | foreach ($ReqParaArray as $key => $value) 52 | { 53 | if (!$isFirst) 54 | { 55 | $SigTxt = $SigTxt."&"; 56 | } 57 | $isFirst= false; 58 | 59 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 60 | if(strpos($key, '_')) 61 | { 62 | $key = str_replace('_', '.', $key); 63 | } 64 | 65 | $SigTxt=$SigTxt.$key."=".$value; 66 | } 67 | 68 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 69 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 70 | 71 | 72 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 73 | $Req = "Signature=".urlencode($Signature); 74 | foreach ($ReqParaArray as $key => $value) 75 | { 76 | $Req=$Req."&".$key."=".urlencode($value); 77 | } 78 | 79 | /*********************************发送请求********************************/ 80 | if($HttpMethod === 'GET') 81 | { 82 | if($isHttps === true) 83 | { 84 | $Req="https://".$FullHttpUrl."?".$Req; 85 | } 86 | else 87 | { 88 | $Req="http://".$FullHttpUrl."?".$Req; 89 | } 90 | 91 | $Rsp = file_get_contents($Req); 92 | 93 | } 94 | else 95 | { 96 | if($isHttps === true) 97 | { 98 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 99 | } 100 | else 101 | { 102 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 103 | } 104 | } 105 | 106 | var_export(json_decode($Rsp,true)); 107 | } 108 | 109 | function SendPost($FullHttpUrl, $Req, $isHttps) 110 | { 111 | 112 | $ch = curl_init(); 113 | curl_setopt($ch, CURLOPT_POST, 1); 114 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 115 | 116 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 117 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 118 | if ($isHttps === true) { 119 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 120 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 121 | } 122 | 123 | $result = curl_exec($ch); 124 | 125 | return $result; 126 | } 127 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/GetHostInfoByIds.php: -------------------------------------------------------------------------------- 1 | 253, 10 | "ids.1" => 326, 11 | ); 12 | 13 | $HttpUrl="cdn.api.qcloud.com"; 14 | 15 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 16 | $HttpMethod="POST"; 17 | 18 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 19 | $isHttps =true; 20 | 21 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 22 | $COMMON_PARAMS = array( 23 | 'Nonce' => rand(), 24 | 'Timestamp' =>time(NULL), 25 | 'Action' =>$action, 26 | 'SecretId' => $secretId, 27 | ); 28 | 29 | /***********************************************************************************/ 30 | 31 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 32 | 33 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 34 | { 35 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 36 | 37 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 38 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 39 | ksort($ReqParaArray); 40 | 41 | /**********************************生成签名原文********************************** 42 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 43 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 44 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 45 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 46 | * ****************************************************************************/ 47 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 48 | 49 | $isFirst = true; 50 | foreach ($ReqParaArray as $key => $value) 51 | { 52 | if (!$isFirst) 53 | { 54 | $SigTxt = $SigTxt."&"; 55 | } 56 | $isFirst= false; 57 | 58 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 59 | if(strpos($key, '_')) 60 | { 61 | $key = str_replace('_', '.', $key); 62 | } 63 | 64 | $SigTxt=$SigTxt.$key."=".$value; 65 | } 66 | 67 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 68 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 69 | 70 | 71 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 72 | $Req = "Signature=".urlencode($Signature); 73 | foreach ($ReqParaArray as $key => $value) 74 | { 75 | $Req=$Req."&".$key."=".urlencode($value); 76 | } 77 | 78 | /*********************************发送请求********************************/ 79 | if($HttpMethod === 'GET') 80 | { 81 | if($isHttps === true) 82 | { 83 | $Req="https://".$FullHttpUrl."?".$Req; 84 | } 85 | else 86 | { 87 | $Req="http://".$FullHttpUrl."?".$Req; 88 | } 89 | 90 | $Rsp = file_get_contents($Req); 91 | 92 | } 93 | else 94 | { 95 | if($isHttps === true) 96 | { 97 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 98 | } 99 | else 100 | { 101 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 102 | } 103 | } 104 | 105 | var_export(json_decode($Rsp,true)); 106 | } 107 | 108 | function SendPost($FullHttpUrl, $Req, $isHttps) 109 | { 110 | 111 | $ch = curl_init(); 112 | curl_setopt($ch, CURLOPT_POST, 1); 113 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 114 | 115 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 116 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 117 | if ($isHttps === true) { 118 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 119 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 120 | } 121 | 122 | $result = curl_exec($ch); 123 | 124 | return $result; 125 | } 126 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/OfflineHost.php: -------------------------------------------------------------------------------- 1 | 862, 18 | ); 19 | 20 | $HttpUrl="cdn.api.qcloud.com"; 21 | 22 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 23 | $HttpMethod="POST"; 24 | 25 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 26 | $isHttps =true; 27 | 28 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 29 | $COMMON_PARAMS = array( 30 | 'Nonce' => rand(), 31 | 'Timestamp' =>time(NULL), 32 | 'Action' =>$action, 33 | 'SecretId' => $secretId, 34 | ); 35 | 36 | /***********************************************************************************/ 37 | 38 | 39 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 40 | 41 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 42 | { 43 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 44 | 45 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 46 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 47 | ksort($ReqParaArray); 48 | 49 | /**********************************生成签名原文********************************** 50 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 51 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 52 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 53 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 54 | * ****************************************************************************/ 55 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 56 | 57 | $isFirst = true; 58 | foreach ($ReqParaArray as $key => $value) 59 | { 60 | if (!$isFirst) 61 | { 62 | $SigTxt = $SigTxt."&"; 63 | } 64 | $isFirst= false; 65 | 66 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 67 | if(strpos($key, '_')) 68 | { 69 | $key = str_replace('_', '.', $key); 70 | } 71 | 72 | $SigTxt=$SigTxt.$key."=".$value; 73 | } 74 | 75 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 76 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 77 | 78 | 79 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 80 | $Req = "Signature=".urlencode($Signature); 81 | foreach ($ReqParaArray as $key => $value) 82 | { 83 | $Req=$Req."&".$key."=".urlencode($value); 84 | } 85 | 86 | /*********************************发送请求********************************/ 87 | if($HttpMethod === 'GET') 88 | { 89 | if($isHttps === true) 90 | { 91 | $Req="https://".$FullHttpUrl."?".$Req; 92 | } 93 | else 94 | { 95 | $Req="http://".$FullHttpUrl."?".$Req; 96 | } 97 | 98 | $Rsp = file_get_contents($Req); 99 | 100 | } 101 | else 102 | { 103 | if($isHttps === true) 104 | { 105 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 106 | } 107 | else 108 | { 109 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 110 | } 111 | } 112 | 113 | var_export(json_decode($Rsp,true)); 114 | } 115 | 116 | function SendPost($FullHttpUrl, $Req, $isHttps) 117 | { 118 | 119 | $ch = curl_init(); 120 | curl_setopt($ch, CURLOPT_POST, 1); 121 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 122 | 123 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 124 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 125 | if ($isHttps === true) { 126 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 128 | } 129 | 130 | $result = curl_exec($ch); 131 | 132 | return $result; 133 | } 134 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/OnlineHost.php: -------------------------------------------------------------------------------- 1 | 862, 18 | ); 19 | 20 | $HttpUrl="cdn.api.qcloud.com"; 21 | 22 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 23 | $HttpMethod="POST"; 24 | 25 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 26 | $isHttps =true; 27 | 28 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 29 | $COMMON_PARAMS = array( 30 | 'Nonce' => rand(), 31 | 'Timestamp' =>time(NULL), 32 | 'Action' =>$action, 33 | 'SecretId' => $secretId, 34 | ); 35 | 36 | /***********************************************************************************/ 37 | 38 | 39 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 40 | 41 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 42 | { 43 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 44 | 45 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 46 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 47 | ksort($ReqParaArray); 48 | 49 | /**********************************生成签名原文********************************** 50 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 51 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 52 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 53 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 54 | * ****************************************************************************/ 55 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 56 | 57 | $isFirst = true; 58 | foreach ($ReqParaArray as $key => $value) 59 | { 60 | if (!$isFirst) 61 | { 62 | $SigTxt = $SigTxt."&"; 63 | } 64 | $isFirst= false; 65 | 66 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 67 | if(strpos($key, '_')) 68 | { 69 | $key = str_replace('_', '.', $key); 70 | } 71 | 72 | $SigTxt=$SigTxt.$key."=".$value; 73 | } 74 | 75 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 76 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 77 | 78 | 79 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 80 | $Req = "Signature=".urlencode($Signature); 81 | foreach ($ReqParaArray as $key => $value) 82 | { 83 | $Req=$Req."&".$key."=".urlencode($value); 84 | } 85 | 86 | /*********************************发送请求********************************/ 87 | if($HttpMethod === 'GET') 88 | { 89 | if($isHttps === true) 90 | { 91 | $Req="https://".$FullHttpUrl."?".$Req; 92 | } 93 | else 94 | { 95 | $Req="http://".$FullHttpUrl."?".$Req; 96 | } 97 | 98 | $Rsp = file_get_contents($Req); 99 | 100 | } 101 | else 102 | { 103 | if($isHttps === true) 104 | { 105 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 106 | } 107 | else 108 | { 109 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 110 | } 111 | } 112 | 113 | var_export(json_decode($Rsp,true)); 114 | } 115 | 116 | function SendPost($FullHttpUrl, $Req, $isHttps) 117 | { 118 | 119 | $ch = curl_init(); 120 | curl_setopt($ch, CURLOPT_POST, 1); 121 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 122 | 123 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 124 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 125 | if ($isHttps === true) { 126 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 128 | } 129 | 130 | $result = curl_exec($ch); 131 | 132 | return $result; 133 | } 134 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/RefreshCdnDir.php: -------------------------------------------------------------------------------- 1 | 'http://foo.bar.com/dir0/', 18 | 'dirs.1'=> 'http://foo.bar.com/dir1/', 19 | ); 20 | 21 | $HttpUrl="cdn.api.qcloud.com"; 22 | 23 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 24 | $HttpMethod="POST"; 25 | 26 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 27 | $isHttps =true; 28 | 29 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 30 | $COMMON_PARAMS = array( 31 | 'Nonce' => rand(), 32 | 'Timestamp' =>time(NULL), 33 | 'Action' =>$action, 34 | 'SecretId' => $secretId, 35 | ); 36 | 37 | /***********************************************************************************/ 38 | 39 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 40 | 41 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 42 | { 43 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 44 | 45 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 46 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 47 | ksort($ReqParaArray); 48 | 49 | /**********************************生成签名原文********************************** 50 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 51 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 52 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 53 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 54 | * ****************************************************************************/ 55 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 56 | 57 | $isFirst = true; 58 | foreach ($ReqParaArray as $key => $value) 59 | { 60 | if (!$isFirst) 61 | { 62 | $SigTxt = $SigTxt."&"; 63 | } 64 | $isFirst= false; 65 | 66 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 67 | if(strpos($key, '_')) 68 | { 69 | $key = str_replace('_', '.', $key); 70 | } 71 | 72 | $SigTxt=$SigTxt.$key."=".$value; 73 | } 74 | 75 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 76 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 77 | 78 | 79 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 80 | $Req = "Signature=".urlencode($Signature); 81 | foreach ($ReqParaArray as $key => $value) 82 | { 83 | $Req=$Req."&".$key."=".urlencode($value); 84 | } 85 | 86 | /*********************************发送请求********************************/ 87 | if($HttpMethod === 'GET') 88 | { 89 | if($isHttps === true) 90 | { 91 | $Req="https://".$FullHttpUrl."?".$Req; 92 | } 93 | else 94 | { 95 | $Req="http://".$FullHttpUrl."?".$Req; 96 | } 97 | 98 | $Rsp = file_get_contents($Req); 99 | 100 | } 101 | else 102 | { 103 | if($isHttps === true) 104 | { 105 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 106 | } 107 | else 108 | { 109 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 110 | } 111 | } 112 | 113 | var_export(json_decode($Rsp,true)); 114 | } 115 | 116 | function SendPost($FullHttpUrl, $Req, $isHttps) 117 | { 118 | 119 | $ch = curl_init(); 120 | curl_setopt($ch, CURLOPT_POST, 1); 121 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 122 | 123 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 124 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 125 | if ($isHttps === true) { 126 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 128 | } 129 | 130 | $result = curl_exec($ch); 131 | 132 | return $result; 133 | } 134 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/RefreshCdnUrl.php: -------------------------------------------------------------------------------- 1 | 'http://ping.cdn.qcloud.com/ping/t0.css', 17 | 'urls.1'=> 'http://ping.cdn.qcloud.com/ping/t1.css', 18 | ); 19 | 20 | $HttpUrl="cdn.api.qcloud.com"; 21 | 22 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 23 | $HttpMethod="POST"; 24 | 25 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 26 | $isHttps =true; 27 | 28 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 29 | $COMMON_PARAMS = array( 30 | 'Nonce' => rand(), 31 | 'Timestamp' =>time(NULL), 32 | 'Action' =>$action, 33 | 'SecretId' => $secretId, 34 | ); 35 | 36 | /***********************************************************************************/ 37 | 38 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 39 | 40 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 41 | { 42 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 43 | 44 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 45 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 46 | ksort($ReqParaArray); 47 | 48 | /**********************************生成签名原文********************************** 49 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 50 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 51 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 52 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 53 | * ****************************************************************************/ 54 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 55 | 56 | $isFirst = true; 57 | foreach ($ReqParaArray as $key => $value) 58 | { 59 | if (!$isFirst) 60 | { 61 | $SigTxt = $SigTxt."&"; 62 | } 63 | $isFirst= false; 64 | 65 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 66 | if(strpos($key, '_')) 67 | { 68 | $key = str_replace('_', '.', $key); 69 | } 70 | 71 | $SigTxt=$SigTxt.$key."=".$value; 72 | } 73 | 74 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 75 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 76 | 77 | 78 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 79 | $Req = "Signature=".urlencode($Signature); 80 | foreach ($ReqParaArray as $key => $value) 81 | { 82 | $Req=$Req."&".$key."=".urlencode($value); 83 | } 84 | 85 | /*********************************发送请求********************************/ 86 | if($HttpMethod === 'GET') 87 | { 88 | if($isHttps === true) 89 | { 90 | $Req="https://".$FullHttpUrl."?".$Req; 91 | } 92 | else 93 | { 94 | $Req="http://".$FullHttpUrl."?".$Req; 95 | } 96 | 97 | $Rsp = file_get_contents($Req); 98 | 99 | } 100 | else 101 | { 102 | if($isHttps === true) 103 | { 104 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 105 | } 106 | else 107 | { 108 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 109 | } 110 | } 111 | 112 | var_export(json_decode($Rsp,true)); 113 | } 114 | 115 | function SendPost($FullHttpUrl, $Req, $isHttps) 116 | { 117 | 118 | $ch = curl_init(); 119 | curl_setopt($ch, CURLOPT_POST, 1); 120 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 121 | 122 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 123 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 124 | if ($isHttps === true) { 125 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 126 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 127 | } 128 | 129 | $result = curl_exec($ch); 130 | 131 | return $result; 132 | } 133 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/UpdateCache.php: -------------------------------------------------------------------------------- 1 | 862, 18 | "cache" => "[[0,\"all\", 1023448]]", 19 | ); 20 | 21 | $HttpUrl="cdn.api.qcloud.com"; 22 | 23 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 24 | $HttpMethod="POST"; 25 | 26 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 27 | $isHttps =true; 28 | 29 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 30 | $COMMON_PARAMS = array( 31 | 'Nonce' => rand(), 32 | 'Timestamp' =>time(NULL), 33 | 'Action' =>$action, 34 | 'SecretId' => $secretId, 35 | ); 36 | 37 | /***********************************************************************************/ 38 | 39 | 40 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 41 | 42 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 43 | { 44 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 45 | 46 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 47 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 48 | ksort($ReqParaArray); 49 | 50 | /**********************************生成签名原文********************************** 51 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 52 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 53 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 54 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 55 | * ****************************************************************************/ 56 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 57 | 58 | $isFirst = true; 59 | foreach ($ReqParaArray as $key => $value) 60 | { 61 | if (!$isFirst) 62 | { 63 | $SigTxt = $SigTxt."&"; 64 | } 65 | $isFirst= false; 66 | 67 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 68 | if(strpos($key, '_')) 69 | { 70 | $key = str_replace('_', '.', $key); 71 | } 72 | 73 | $SigTxt=$SigTxt.$key."=".$value; 74 | } 75 | 76 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 77 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 78 | 79 | 80 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 81 | $Req = "Signature=".urlencode($Signature); 82 | foreach ($ReqParaArray as $key => $value) 83 | { 84 | $Req=$Req."&".$key."=".urlencode($value); 85 | } 86 | 87 | /*********************************发送请求********************************/ 88 | if($HttpMethod === 'GET') 89 | { 90 | if($isHttps === true) 91 | { 92 | $Req="https://".$FullHttpUrl."?".$Req; 93 | } 94 | else 95 | { 96 | $Req="http://".$FullHttpUrl."?".$Req; 97 | } 98 | 99 | $Rsp = file_get_contents($Req); 100 | 101 | } 102 | else 103 | { 104 | if($isHttps === true) 105 | { 106 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 107 | } 108 | else 109 | { 110 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 111 | } 112 | } 113 | 114 | var_export(json_decode($Rsp,true)); 115 | } 116 | 117 | function SendPost($FullHttpUrl, $Req, $isHttps) 118 | { 119 | 120 | $ch = curl_init(); 121 | curl_setopt($ch, CURLOPT_POST, 1); 122 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 123 | 124 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 125 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 126 | if ($isHttps === true) { 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 128 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 129 | } 130 | 131 | $result = curl_exec($ch); 132 | 133 | return $result; 134 | } 135 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/UpdateCdnConfig.php: -------------------------------------------------------------------------------- 1 | 862, 27 | "projectId" => 0, 28 | "cacheMode" => "custom", 29 | "cache" => "[[0,\"all\", 1023448]]", 30 | "refer" => "[1,[\"qq.baidu.com\", \"v.qq.com\"]]", 31 | "fwdHost" => "qq.com.cn", 32 | "fullUrl" => "off", 33 | ); 34 | 35 | $HttpUrl="cdn.api.qcloud.com"; 36 | 37 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 38 | $HttpMethod="POST"; 39 | 40 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 41 | $isHttps =true; 42 | 43 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 44 | $COMMON_PARAMS = array( 45 | 'Nonce' => rand(), 46 | 'Timestamp' =>time(NULL), 47 | 'Action' =>$action, 48 | 'SecretId' => $secretId, 49 | ); 50 | 51 | /***********************************************************************************/ 52 | 53 | 54 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 55 | 56 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 57 | { 58 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 59 | 60 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 61 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 62 | ksort($ReqParaArray); 63 | 64 | /**********************************生成签名原文********************************** 65 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 66 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 67 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 68 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 69 | * ****************************************************************************/ 70 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 71 | 72 | $isFirst = true; 73 | foreach ($ReqParaArray as $key => $value) 74 | { 75 | if (!$isFirst) 76 | { 77 | $SigTxt = $SigTxt."&"; 78 | } 79 | $isFirst= false; 80 | 81 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 82 | if(strpos($key, '_')) 83 | { 84 | $key = str_replace('_', '.', $key); 85 | } 86 | 87 | $SigTxt=$SigTxt.$key."=".$value; 88 | } 89 | 90 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 91 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 92 | 93 | 94 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 95 | $Req = "Signature=".urlencode($Signature); 96 | foreach ($ReqParaArray as $key => $value) 97 | { 98 | $Req=$Req."&".$key."=".urlencode($value); 99 | } 100 | 101 | /*********************************发送请求********************************/ 102 | if($HttpMethod === 'GET') 103 | { 104 | if($isHttps === true) 105 | { 106 | $Req="https://".$FullHttpUrl."?".$Req; 107 | } 108 | else 109 | { 110 | $Req="http://".$FullHttpUrl."?".$Req; 111 | } 112 | 113 | $Rsp = file_get_contents($Req); 114 | 115 | } 116 | else 117 | { 118 | if($isHttps === true) 119 | { 120 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 121 | } 122 | else 123 | { 124 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 125 | } 126 | } 127 | 128 | var_export(json_decode($Rsp,true)); 129 | } 130 | 131 | function SendPost($FullHttpUrl, $Req, $isHttps) 132 | { 133 | 134 | $ch = curl_init(); 135 | curl_setopt($ch, CURLOPT_POST, 1); 136 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 137 | 138 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 139 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 140 | if ($isHttps === true) { 141 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 142 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 143 | } 144 | 145 | $result = curl_exec($ch); 146 | 147 | return $result; 148 | } 149 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/UpdateCdnHost.php: -------------------------------------------------------------------------------- 1 | 862, 18 | "host" => 'test.com', 19 | "origin" => '1.1.1.1', 20 | ); 21 | 22 | $HttpUrl="cdn.api.qcloud.com"; 23 | 24 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 25 | $HttpMethod="POST"; 26 | 27 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 28 | $isHttps =true; 29 | 30 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 31 | $COMMON_PARAMS = array( 32 | 'Nonce' => rand(), 33 | 'Timestamp' =>time(NULL), 34 | 'Action' =>$action, 35 | 'SecretId' => $secretId, 36 | ); 37 | 38 | /***********************************************************************************/ 39 | 40 | 41 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 42 | 43 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 44 | { 45 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 46 | 47 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 48 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 49 | ksort($ReqParaArray); 50 | 51 | /**********************************生成签名原文********************************** 52 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 53 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 54 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 55 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 56 | * ****************************************************************************/ 57 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 58 | 59 | $isFirst = true; 60 | foreach ($ReqParaArray as $key => $value) 61 | { 62 | if (!$isFirst) 63 | { 64 | $SigTxt = $SigTxt."&"; 65 | } 66 | $isFirst= false; 67 | 68 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 69 | if(strpos($key, '_')) 70 | { 71 | $key = str_replace('_', '.', $key); 72 | } 73 | 74 | $SigTxt=$SigTxt.$key."=".$value; 75 | } 76 | 77 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 78 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 79 | 80 | 81 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 82 | $Req = "Signature=".urlencode($Signature); 83 | foreach ($ReqParaArray as $key => $value) 84 | { 85 | $Req=$Req."&".$key."=".urlencode($value); 86 | } 87 | 88 | /*********************************发送请求********************************/ 89 | if($HttpMethod === 'GET') 90 | { 91 | if($isHttps === true) 92 | { 93 | $Req="https://".$FullHttpUrl."?".$Req; 94 | } 95 | else 96 | { 97 | $Req="http://".$FullHttpUrl."?".$Req; 98 | } 99 | 100 | $Rsp = file_get_contents($Req); 101 | 102 | } 103 | else 104 | { 105 | if($isHttps === true) 106 | { 107 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 108 | } 109 | else 110 | { 111 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 112 | } 113 | } 114 | 115 | var_export(json_decode($Rsp,true)); 116 | } 117 | 118 | function SendPost($FullHttpUrl, $Req, $isHttps) 119 | { 120 | 121 | $ch = curl_init(); 122 | curl_setopt($ch, CURLOPT_POST, 1); 123 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 124 | 125 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 126 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 127 | if ($isHttps === true) { 128 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 129 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 130 | } 131 | 132 | $result = curl_exec($ch); 133 | 134 | return $result; 135 | } 136 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/php/UpdateCdnProject.php: -------------------------------------------------------------------------------- 1 | 862, 19 | "projectId" => 0, 20 | ); 21 | 22 | $HttpUrl="cdn.api.qcloud.com"; 23 | 24 | /*除非有特殊说明,如MultipartUploadVodFile,其它接口都支持GET及POST*/ 25 | $HttpMethod="POST"; 26 | 27 | /*是否https协议,大部分接口都必须为https,只有少部分接口除外(如MultipartUploadVodFile)*/ 28 | $isHttps =true; 29 | 30 | /*下面这五个参数为所有接口的 公共参数;对于某些接口没有地域概念,则不用传递Region(如DescribeDeals)*/ 31 | $COMMON_PARAMS = array( 32 | 'Nonce' => rand(), 33 | 'Timestamp' =>time(NULL), 34 | 'Action' =>$action, 35 | 'SecretId' => $secretId, 36 | ); 37 | 38 | /***********************************************************************************/ 39 | 40 | CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps); 41 | 42 | function CreateRequest($HttpUrl,$HttpMethod,$COMMON_PARAMS,$secretKey, $PRIVATE_PARAMS, $isHttps) 43 | { 44 | $FullHttpUrl = $HttpUrl."/v2/index.php"; 45 | 46 | /***************对请求参数 按参数名 做字典序升序排列,注意此排序区分大小写*************/ 47 | $ReqParaArray = array_merge($COMMON_PARAMS, $PRIVATE_PARAMS); 48 | ksort($ReqParaArray); 49 | 50 | /**********************************生成签名原文********************************** 51 | * 将 请求方法, URI地址,及排序好的请求参数 按照下面格式 拼接在一起, 生成签名原文,此请求中的原文为 52 | * GETcvm.api.qcloud.com/v2/index.php?Action=DescribeInstances&Nonce=345122&Region=gz 53 | * &SecretId=AKIDz8krbsJ5yKBZQ ·1pn74WFkmLPx3gnPhESA&Timestamp=1408704141 54 | * &instanceIds.0=qcvm12345&instanceIds.1=qcvm56789 55 | * ****************************************************************************/ 56 | $SigTxt = $HttpMethod.$FullHttpUrl."?"; 57 | 58 | $isFirst = true; 59 | foreach ($ReqParaArray as $key => $value) 60 | { 61 | if (!$isFirst) 62 | { 63 | $SigTxt = $SigTxt."&"; 64 | } 65 | $isFirst= false; 66 | 67 | /*拼接签名原文时,如果参数名称中携带_,需要替换成.*/ 68 | if(strpos($key, '_')) 69 | { 70 | $key = str_replace('_', '.', $key); 71 | } 72 | 73 | $SigTxt=$SigTxt.$key."=".$value; 74 | } 75 | 76 | /*********************根据签名原文字符串 $SigTxt,生成签名 Signature******************/ 77 | $Signature = base64_encode(hash_hmac('sha1', $SigTxt, $secretKey, true)); 78 | 79 | 80 | /***************拼接请求串,对于请求参数及签名,需要进行urlencode编码********************/ 81 | $Req = "Signature=".urlencode($Signature); 82 | foreach ($ReqParaArray as $key => $value) 83 | { 84 | $Req=$Req."&".$key."=".urlencode($value); 85 | } 86 | 87 | /*********************************发送请求********************************/ 88 | if($HttpMethod === 'GET') 89 | { 90 | if($isHttps === true) 91 | { 92 | $Req="https://".$FullHttpUrl."?".$Req; 93 | } 94 | else 95 | { 96 | $Req="http://".$FullHttpUrl."?".$Req; 97 | } 98 | 99 | $Rsp = file_get_contents($Req); 100 | 101 | } 102 | else 103 | { 104 | if($isHttps === true) 105 | { 106 | $Rsp= SendPost("https://".$FullHttpUrl,$Req,$isHttps); 107 | } 108 | else 109 | { 110 | $Rsp= SendPost("http://".$FullHttpUrl,$Req,$isHttps); 111 | } 112 | } 113 | 114 | var_export(json_decode($Rsp,true)); 115 | } 116 | 117 | function SendPost($FullHttpUrl, $Req, $isHttps) 118 | { 119 | 120 | $ch = curl_init(); 121 | curl_setopt($ch, CURLOPT_POST, 1); 122 | curl_setopt($ch, CURLOPT_POSTFIELDS, $Req); 123 | 124 | curl_setopt($ch, CURLOPT_URL, $FullHttpUrl); 125 | curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 126 | if ($isHttps === true) { 127 | curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 128 | curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 129 | } 130 | 131 | $result = curl_exec($ch); 132 | 133 | return $result; 134 | } 135 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/python/QcloudCdnTools_V2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | import os 5 | import hashlib 6 | import urllib 7 | import requests 8 | import binascii 9 | import hmac 10 | import copy 11 | import random 12 | import sys 13 | import time 14 | from pprint import pprint 15 | from optparse import OptionParser 16 | from requests.packages.urllib3.exceptions import InsecurePlatformWarning 17 | requests.packages.urllib3.disable_warnings(InsecurePlatformWarning) 18 | from requests.packages.urllib3.exceptions import InsecureRequestWarning 19 | requests.packages.urllib3.disable_warnings(InsecureRequestWarning) 20 | 21 | reload(sys) 22 | sys.setdefaultencoding("utf-8") 23 | 24 | try: import simplejson as json 25 | except: import json 26 | 27 | 28 | class Sign: 29 | def __init__(self, secretId, secretKey): 30 | self.secretId = secretId 31 | self.secretKey = secretKey 32 | 33 | def make(self, requestHost, requestUri, params, method = 'GET'): 34 | srcStr = method.upper() + requestHost + requestUri + '?' + "&".join(k.replace("_",".") + "=" + str(params[k]) for k in sorted(params.keys())) 35 | hashed = hmac.new(self.secretKey, srcStr, hashlib.sha1) 36 | return binascii.b2a_base64(hashed.digest())[:-1] 37 | 38 | class Request: 39 | timeout = 10 40 | version = 'Python_Tools' 41 | def __init__(self, secretId, secretKey): 42 | self.secretId = secretId 43 | self.secretKey = secretKey 44 | 45 | def send(self, requestHost, requestUri, params, files = {}, method = 'GET', debug = 0): 46 | params['RequestClient'] = Request.version 47 | params['SecretId'] = self.secretId 48 | sign = Sign(self.secretId, self.secretKey) 49 | params['Signature'] = sign.make(requestHost, requestUri, params, method) 50 | 51 | url = 'https://%s%s' % (requestHost, requestUri) 52 | 53 | if debug: 54 | print method.upper(), url 55 | print 'Request Args:' 56 | pprint(params) 57 | if method.upper() == 'GET': 58 | req = requests.get(url, params=params, timeout=Request.timeout,verify=False) 59 | else: 60 | req = requests.post(url, data=params, files=files, timeout=Request.timeout,verify=False) 61 | 62 | if debug: 63 | print "Response:", req.status_code, req.text 64 | if req.status_code != requests.codes.ok: 65 | req.raise_for_status() 66 | 67 | rsp = {} 68 | try: 69 | rsp = json.loads(req.text) 70 | except: 71 | raise ValueError, "Error: response is not json\n%s" % req.text 72 | 73 | code = rsp.get("code", -1) 74 | message = rsp.get("message", req.text) 75 | if rsp.get('code', -404) != 0: 76 | raise ValueError, "Error: code=%s, message=%s" % (code, message) 77 | if rsp.get('data', None) is None: 78 | print 'request is success.' 79 | else: 80 | print rsp['data'] 81 | 82 | 83 | 84 | 85 | def Name(name): 86 | up = False 87 | new_name = "" 88 | for i in name: 89 | if i == '_': 90 | up = True 91 | continue 92 | if up: 93 | new_name += i.upper() 94 | else: 95 | new_name += i 96 | up = False 97 | return new_name 98 | 99 | 100 | class Cdn: 101 | def __init__(self): 102 | self.params = { 103 | 'Region': 'gz', 104 | 'Nonce': random.randint(1, sys.maxint), 105 | 'Timestamp': int(time.time()), 106 | } 107 | self.files = {} 108 | self.host = 'cdn.api.qcloud.com' 109 | self.uri = '/v2/index.php' 110 | self.method = "POST" 111 | self.debug = 1 112 | 113 | def parse_args(self): 114 | actions = [] 115 | for method in dir(self): 116 | if method[0].isupper(): 117 | actions.append( method ) 118 | 119 | usage='usage: %prog Action [options]\nThis is a command line tools to access Qcloud API.\n\nSupport Actions:\n '+"\n ".join(actions) 120 | self.parser = OptionParser(usage=usage) 121 | from sys import argv 122 | if len(argv) < 2 or argv[1] not in actions: 123 | self.parser.print_help() 124 | return 0 125 | 126 | action = argv[1] 127 | self.params['Action'] = action 128 | usage='usage: %%prog Action [options]\n\nThis is help message for action "%s"\nMore Usage: http://www.qcloud.com/wiki/v2/%s' % (action, action) 129 | self.parser = OptionParser(usage=usage) 130 | self.parser.add_option('--debug', dest='debug', action="store_true", default=False, help='Print debug message') 131 | self.parser.add_option('-u', '--secret_id', dest='secret_id', help='Secret ID from ') 132 | self.parser.add_option('-p', '--secret_key', dest='secret_key', help='Secret Key from ') 133 | getattr(self, action)() 134 | if len(argv) == 2: 135 | self.parser.print_help() 136 | return 0 137 | 138 | (options, args) = self.parser.parse_args() # parse again 139 | self.debug = options.debug 140 | for key in dir(options): 141 | if not key.startswith("__") and getattr(options, key) is None: 142 | raise KeyError, ('Error: Please provide options --%s' % key) 143 | 144 | 145 | for option in self.parser.option_list: 146 | opt = option.dest 147 | if opt not in [None, 'secret_id', 'secret_key', 'debug']: 148 | self.params[ Name(opt) ] = getattr(options, opt) 149 | 150 | self.options = options 151 | method = 'get_params_' + action 152 | if hasattr(self, method): getattr(self, method)() 153 | 154 | # format params 155 | for key, value in self.params.items(): 156 | if value == '': 157 | del self.params[key] 158 | if isinstance(value, list): 159 | del self.params[key] 160 | for idx, val in enumerate(value): 161 | self.params["%s.%s"%(key, idx)] = val 162 | 163 | request = Request(options.secret_id, options.secret_key) 164 | return request.send(self.host, self.uri, self.params, self.files, self.method, self.debug) 165 | 166 | 167 | def DescribeCdnHosts(self): 168 | self.parser.add_option('--offset', dest='offset', default='', help="offset") 169 | self.parser.add_option('--limit', dest='limit', default='',help="limit") 170 | 171 | def RefreshCdnUrl(self): 172 | self.parser.add_option('--urls', dest='urls', default=[], action="append", help="Flush the cache of these URLs(use multi --urls)") 173 | self.parser.add_option('--urls-from', dest='urls_from', default="", metavar="FILE", help="Flush the cache of these URLs(one url per line)") 174 | 175 | def RefreshCdnDir(self): 176 | self.parser.add_option('--dirs', dest='dirs', default=[], action="append", help="Flush the cache of these DIRs(use multi --dirs)") 177 | self.parser.add_option('--dirs-from', dest='dirs_from', default="", metavar="FILE", help="Flush the cache of these URLs(one dir per line)") 178 | 179 | def get_params_RefreshCdnUrl(self): 180 | if self.options.urls_from: 181 | f = open(self.options.urls_from) 182 | self.params["urls"] = [p.strip() for p in f.readlines()] 183 | elif not self.options.urls: 184 | raise ValueError, "Please provide --urls or --urls-from" 185 | del self.params['urlsFrom'] 186 | 187 | def GetCdnRefreshLog(self): 188 | self.parser.add_option('--startDate', dest='startDate', help="Start Date, e.g. '2015-04-20'") 189 | self.parser.add_option('--endDate', dest='endDate', help="end Date, e.g. '2015-04-20'") 190 | self.parser.add_option('--url', dest='url', default="", help="optional search url") 191 | 192 | def UpdateCdnHost(self): 193 | self.parser.add_option('--origin', dest='origin', help="CDN origin server address") 194 | self.parser.add_option('--host', dest='host', help="CDN host") 195 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 196 | 197 | def DeleteCdnHost(self): 198 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 199 | 200 | def DescribeCdnHostDetailedInfo(self): 201 | self.parser.add_option('--startDate', dest='startDate', help="Start Date, e.g. '2015-04-20 00:00:00'") 202 | self.parser.add_option('--endDate', dest='endDate', help="end Date, e.g. '2015-04-20 23:59:59'") 203 | self.parser.add_option('--statType', dest='statType', choices=['bandwidth','flux','requests','ip_visits','cache'], help="stat type") 204 | self.parser.add_option('--hosts', dest='hosts', default=[], action="append", help="Options Filter by these hosts(use multi --hosts)") 205 | self.parser.add_option('--projects', dest='projects', default=[], action="append", help="Optional Filter by these project ids(use multi --projects)") 206 | 207 | def DescribeCdnHostInfo(self): 208 | self.parser.add_option('--startDate', dest='startDate', help="Start Date, e.g. '2015-04-20 00:00:00'") 209 | self.parser.add_option('--endDate', dest='endDate', help="end Date, e.g. '2015-04-20 23:59:59'") 210 | self.parser.add_option('--statType', dest='statType', choices=['bandwidth','flux','requests','ip_visits','cache'], help="stat type") 211 | self.parser.add_option('--hosts', dest='hosts', default=[], action="append", help="Options Filter by these hosts(use multi --hosts)") 212 | self.parser.add_option('--projects', dest='projects', default=[], action="append", help="Optional Filter by these project ids(use multi --projects)") 213 | 214 | def AddCdnHost(self): 215 | self.parser.add_option('--host', dest='host', help="CDN host") 216 | self.parser.add_option('--origin', dest='origin', default='',help="CDN origin server address") 217 | self.parser.add_option('--hostType', dest='hostType', choices=["cname", "ftp"], help="host type: cname or ftp") 218 | self.parser.add_option('--projectId', dest='projectId', default=0, help="Attach the host to specific project.") 219 | pass 220 | 221 | def UpdateCdnProject(self): 222 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 223 | self.parser.add_option('--projectId', dest='projectId', help="new project id") 224 | 225 | def UpdateCache(self): 226 | self.parser.add_option('--hostId', dest='hostId', default="", help="CDN host ID") 227 | self.parser.add_option('--cache', dest='cache', help="new cache rule. Read the webpage for more details ") 228 | 229 | def OfflineHost(self): 230 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 231 | 232 | def OnlineHost(self): 233 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 234 | 235 | def GenerateLogList(self): 236 | self.parser.add_option('--hostId', dest='hostId', help="CDN host ID") 237 | 238 | def GetCdnMiddleSourceList(self): 239 | pass 240 | 241 | def UpdateCdnConfig(self): 242 | self.parser.add_option('--hostId', dest='hostId', help="CDN host") 243 | self.parser.add_option('--origin', dest='origin', default='', help="CDN origin server address") 244 | self.parser.add_option('--projectId', dest='projectId', default=0, help="Attach the host to specific project.") 245 | self.parser.add_option('--middleResource', dest='middleResource', default='', help="TODO") 246 | self.parser.add_option('--cacheMode', dest='cacheMode', default='', help='simple or custom, learn more by visting -> http://www.qcloud.com/wiki/CDN%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C#CDN.E9.85.8D.E7.BD.AE.E7.AE.A1.E7.90.86.EF.BC.9A.E7.BC.93.E5.AD.98.E6.97.B6.E9.97.B4') 247 | self.parser.add_option('--cache', dest='cache', default=' ', help='TODO') 248 | self.parser.add_option('--refer', dest='refer', default=' ', help='TODO') 249 | self.parser.add_option('--fwdHost', dest='fwdHost', default='', help='the host header when cdn server request origin with') 250 | self.parser.add_option('--fullUrl', dest='fullUrl', default='', help='the requested resource will be stored on cdn server with the full uri as key if this option is turned on, otherwise uri without arguments will be the key') 251 | 252 | def GetHostInfoByHost(self): 253 | self.parser.add_option('--hosts', dest='hosts', default=[], action="append", help="CDN host (use multi --hosts)") 254 | 255 | def GetHostInfoById(self): 256 | self.parser.add_option('--ids', dest='ids', default=[], action="append", help="CDN host ID(use multi --ids)") 257 | 258 | def GetCdnStatTop(self): 259 | self.parser.add_option('--startDate', dest='startDate', help="Start Date, e.g. '2015-04-20'") 260 | self.parser.add_option('--endDate', dest='endDate', help="end Date, e.g. '2015-04-20 '") 261 | self.parser.add_option('--statType', dest='statType', choices=['bandwidth','flux','requests','ip_visits','cache'], help="stat type") 262 | self.parser.add_option('--hosts', dest='hosts', default=[], action="append", help="Options Filter by these hosts(use multi --hosts)") 263 | self.parser.add_option('--projects', dest='projects', default=['0'], action="append", help="Optional Filter by these project ids(use multi --projects)") 264 | self.parser.add_option('--period', dest='period', default=5, help="period to get data") 265 | 266 | 267 | def GetCdnStatusCode(self): 268 | self.parser.add_option('--startDate', dest='startDate', help="startDate, e.g. '2015-04-20'") 269 | self.parser.add_option('--endDate', dest='endDate', help="endDate, e.g. '2015-04-20'") 270 | self.parser.add_option('--sources', dest='sources', default=[],action="append", choices=['oc','middle'], help="sources ,oc or middle") 271 | self.parser.add_option('--hosts', dest='hosts', default=[], action="append", help="Options Filter by these hosts(use multi --hosts)") 272 | self.parser.add_option('--projects', dest='projects', default=[], action="append", help="Optional Filter by these project ids(use multi --projects)") 273 | self.parser.add_option('--period', dest='period', default=5, help="period to get data") 274 | 275 | def main(): 276 | cdn = Cdn() 277 | try: 278 | cdn.parse_args() 279 | except Exception as e: 280 | print e 281 | return 1 282 | 283 | return 0 284 | 285 | 286 | if __name__ == '__main__': 287 | sys.exit(main()) 288 | 289 | -------------------------------------------------------------------------------- /Qcloud_CDN_API/python/README.md: -------------------------------------------------------------------------------- 1 | ## python demo 工具使用方法 2 | 其中 -u参数表示 SECRET_ID -p 参数表示SECRET_KEY,可从https://console.qcloud.com/capi 获取,其余参数参考https://www.qcloud.com/doc/api/231/API%E6%A6%82%E8%A7%88 3 | 4 | ## DescribleCdnHosts 5 | python QcloudCdnTools_V2.py DescribeCdnHosts -u xxxxx -p xxxxxxx 6 | 7 | ## GetHostInfoByHost 8 | python QcloudCdnTools_V2.py GetHostInfoByHost -u xxxxx -p xxxxxxx --hosts xxxxxxxtang.oa.com --hosts www.xxxxxxx.217.oa.com 9 | 10 | ## GetHostInfoById 11 | python QcloudCdnTools_V2.py GetHostInfoById -u xxxxx -p xxxxxxx --ids 184736 --ids 206348 12 | 13 | ## RefreshCdnUrl 14 | python QcloudCdnTools_V2.py RefreshCdnUrl -u xxxxx -p xxxxxxx --urls http://xxxxxxxtang.sp.oa.com/test.php --urls http://xxxxxxxtang.sp.oa.com/test1.php 15 | 16 | ## RefreshCdnDir 17 | python QcloudCdnTools_V2.py RefreshCdnDir -u xxxxx -p xxxxxxx --dirs http://xxxxxxxtang.sp.oa.com/test/ --dirs http://xxxxxxxtang.sp.oa.com/a/ --dirs http://xxxxxxxtang.sp.oa.com/b/ 18 | 19 | ## UpdateCache 20 | python QcloudCdnTools_V2.py UpdateCache -u xxxxx -p xxxxxxx --hostId 206092 --cache [[0,\"all\",1023448]] 21 | 22 | ## UpdateCdnProject 23 | python QcloudCdnTools_V2.py UpdateCdnProject -u xxxxx -p xxxxxxx --hostId 206092 --projectId 0 24 | 25 | ## UpdateCdnHost 26 | python QcloudCdnTools_V2.py UpdateCdnHost -u xxxxx -p xxxxxxx --hostId 206092 --host xxxxxxxtang.vip2.oa.com --origin 1.1.1.2 27 | 28 | ## UpdateCdnConfig 29 | python QcloudCdnTools_V2.py UpdateCdnConfig -u xxxxx -p xxxxxxx --hostId 206084 --projectId 0 --cacheMode custom --cache [[0,\"all\",1023448]] --refer [1,[\"qq.baidu.com\",\"v.qq.com\"]] --fwdHost qq.com.cn --fullUrl off --debug 30 | 31 | ## OfflineHost 32 | python QcloudCdnTools_V2.py OfflineHost -u xxxxx -p xxxxxxx --hostId 206092 33 | 34 | ## AddCdnHost 35 | python QcloudCdnTools_V2.py AddCdnHost -u xxxxx -p xxxxxxx --host evincai.oa.com --projectId 0 --hostType cname --origin 1.1.1.1 36 | 37 | ## OnlineHost 38 | python QcloudCdnTools_V2.py OnlineHost -u xxxxx -p xxxxxxx --hostId 206092 39 | 40 | 41 | ## DeleteCdnHost 42 | python QcloudCdnTools_V2.py DeleteCdnHost -u xxxxx -p xxxxxxx --hostId 81094 43 | 44 | ## GenerateLogList 45 | python QcloudCdnTools_V2.py GenerateLogList -u xxxxx -p xxxxxxx --hostId 206092 46 | 47 | ## GetCdnRefreshLog 48 | python QcloudCdnTools_V2.py GetCdnRefreshLog -u xxxxxxxxxxxx -p xxxxxxxxxxxx --startDate 2016-04-25 --endDate 2016-04-26 49 | 50 | ## GetCdnStatTop 51 | python QcloudCdnTools_V2.py GetCdnStatTop -u xxxxxxxxxxxx -p xxxxxxxxxxxx --startDate 2016-05-08 --endDate 2016-05-09 --statType bandwidth --projects 0 --hosts ping.cdn.qcloud.com --hosts ts6.cache.qcloudcdn.com 52 | 53 | ## GetCdnStatusCode 54 | python QcloudCdnTools_V2.py GetCdnStatusCode -u xxxxxxxxxxxx -p xxxxxxxxxxxx --startDate 2016-05-08 --endDate 2016-05-09 --projects 0 --hosts ping.cdn.qcloud.com --hosts ts6.cache.qcloudcdn.com 55 | 56 | ## DescribeCdnHostDetailedInfo 57 | python QcloudCdnTools_V2.py DescribeCdnHostDetailedInfo -u xxxxxxxxxxxx -p xxxxxxxxxxxx --startDate 2016-05-08 --endDate 2016-05-09 --projects 0 --hosts ping.cdn.qcloud.com --hosts ts6.cache.qcloudcdn.com --statType bandwidth 58 | 59 | ## DescribeCdnHostInfo 60 | python QcloudCdnTools_V2.py DescribeCdnHostInfo -u xxxxxxxxxxxx -p xxxxxxxxxxxx --startDate 2016-05-08 --endDate 2016-05-09 --projects 0 --statType bandwidth --debug 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | ## 腾讯云CDN OpenAPI SDK 3 | 4 | 现有版本: 5 | * [go](https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/go) 6 | * [nodejs](https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/nodejs) 7 | * [php](https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/php) 8 | * [python](https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/python) 9 | * [java](https://github.com/QCloudCDN/CDN_API_SDK/tree/master/Qcloud_CDN_API/java/cdn_openapi_demo/src) 10 | 11 | ## API 概览 12 | 13 | ### 消耗及统计量查询 14 | 15 | | API | 功能说明 | 16 | | ---------------------------------------- | ---------------------------------------- | 17 | | [DescribeCdnHostInfo](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2CDN%E6%B6%88%E8%80%97%E7%BB%9F%E8%AE%A1) | 查询流量、带宽、请求数、IP访问数、命中率等总统计信息 | 18 | | [DescribeCdnHostDetailedInfo](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2CDN%E6%B6%88%E8%80%97%E6%98%8E%E7%BB%86) | 查询流量、带宽、请求数、IP访问数、命中率等统计明细信息,1-3日时间粒度为5分钟,3-7日明细粒度为1小时,7-30日明细粒度为1天 | 19 | | [GetCdnStatusCode](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2%E8%BF%94%E5%9B%9E%E7%A0%81%E7%BB%9F%E8%AE%A1) | 查询返回码 200、206、304、404、416、500 统计明细 | 20 | | [GetCdnStatTop](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2%E6%B6%88%E8%80%97%E6%8E%92%E5%90%8D) | 查询省份、运营商、URL的流量/带宽排名情况,TOP100 | 21 | 22 | 23 | 24 | ### 域名查询 25 | 26 | | API | 功能说明 | 27 | | ---------------------------------------- | -------------------------------- | 28 | | [DescribeCdnHosts](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2%E5%9F%9F%E5%90%8D%E4%BF%A1%E6%81%AF) | 查询所有域名详细信息,包括配置信息,支持分页查询 | 29 | | [GetHostInfoByHost](https://www.qcloud.com/doc/api/231/%E6%A0%B9%E6%8D%AE%E5%9F%9F%E5%90%8D%E6%9F%A5%E8%AF%A2%E5%9F%9F%E5%90%8D%E4%BF%A1%E6%81%AF) | 根据域名查询域名详细信息,包括配置信息,支持多个域名查询 | 30 | | [GetHostInfoById](https://www.qcloud.com/doc/api/231/%E6%A0%B9%E6%8D%AE%E5%9F%9F%E5%90%8DID%E6%9F%A5%E8%AF%A2%E5%9F%9F%E5%90%8D%E4%BF%A1%E6%81%AF) | 根据域名ID查询域名详细信息,包括配置信息,支持多个域名ID查询 | 31 | 32 | 33 | 34 | ### 域名管理 35 | 36 | | API | 功能说明 | 37 | | ---------------------------------------- | ------------------------ | 38 | | [AddCdnHost](https://www.qcloud.com/doc/api/231/%E6%96%B0%E5%A2%9E%E5%8A%A0%E9%80%9F%E5%9F%9F%E5%90%8D)| 接入域名至腾讯云CDN | 39 | | [OnlineHost](https://www.qcloud.com/doc/api/231/%E4%B8%8A%E7%BA%BFCDN%E5%9F%9F%E5%90%8D) | 上线指定CDN域名 | 40 | | [OfflineHost](https://www.qcloud.com/doc/api/231/%E4%B8%8B%E7%BA%BFCDN%E5%9F%9F%E5%90%8D) | 下线指定CDN域名 | 41 | | [DeleteCdnHost](https://www.qcloud.com/doc/api/231/%E5%88%A0%E9%99%A4%E5%8A%A0%E9%80%9F%E5%9F%9F%E5%90%8D) | 删除指定CDN域名 | 42 | | [UpdateCdnHost](https://www.qcloud.com/doc/api/231/%E8%AE%BE%E7%BD%AE%E6%BA%90%E7%AB%99%E4%BF%A1%E6%81%AF) | 修改域名源站设置 | 43 | | [UpdateCdnProject](https://www.qcloud.com/doc/api/231/%E8%AE%BE%E7%BD%AE%E5%9F%9F%E5%90%8D%E6%89%80%E5%B1%9E%E9%A1%B9%E7%9B%AE) | 修改域名所属项目 | 44 | | [UpdateCache](https://www.qcloud.com/doc/api/231/%E8%AE%BE%E7%BD%AE%E7%BC%93%E5%AD%98%E8%A7%84%E5%88%99) | 修改域名对应的缓存规则配置 | 45 | | [UpdateCdnConfig](https://www.qcloud.com/doc/api/231/%E8%AE%BE%E7%BD%AE%E5%9F%9F%E5%90%8D%E9%85%8D%E7%BD%AE) | 对指定域名的缓存、防盗链、回源等各项信息进行设置 | 46 | 47 | 48 | 49 | ### 域名刷新 50 | 51 | | API | 功能说明 | 52 | | ---------------------------------------- | ------------------- | 53 | | [GetCdnRefreshLog](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2%E5%88%B7%E6%96%B0%E7%BA%AA%E5%BD%95) | 查询指定时间区间内,刷新日志、刷新次数 | 54 | | [RefreshCdnUrl](https://www.qcloud.com/doc/api/231/%E5%88%B7%E6%96%B0URL) | 刷新URL | 55 | | [RefreshCdnDir](https://www.qcloud.com/doc/api/231/%E5%88%B7%E6%96%B0%E7%9B%AE%E5%BD%95) | 刷新目录 | 56 | 57 | 58 | 59 | ### 日志查询 60 | 61 | | API | 功能说明 | 62 | | ---------------------------------------- | -------- | 63 | | [GenerateLogList](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2%E6%97%A5%E5%BF%97%E4%B8%8B%E8%BD%BD%E9%93%BE%E6%8E%A5) | 查询日志下载链接 | 64 | 65 | 66 | 67 | ### 辅助工具 68 | 69 | | API | 功能说明 | 70 | | ---------------------------------------- | ------------ | 71 | | [GetCdnMiddleSourceList](https://www.qcloud.com/doc/api/231/%E6%9F%A5%E8%AF%A2CDN%E4%B8%AD%E9%97%B4%E6%BA%90) | 查询CDN中间源IP列表 | 72 | 73 | --------------------------------------------------------------------------------