Example 1

HTTP Requests

Example 1

Top  Previous  Next

Upload ảnh lên https://tinypng.com

với REST API do trang này cung cấp

 

 

- Trước tiên ta vào trang API của nó: https://tinypng.com/developers/reference

 

- Trang này giải thích: Muốn up ảnh lên thì cần phải thực hiện Authentication trước:

 

To use the API you must provide your API key. You can get an API key by registering with your name and email address. Always keep your API key secret!

 

Authentication to the API is done with HTTP Basic Auth. All requests require an Authorization header that contains a Base64 digest of the authentication string api:YOUR_API_KEY where YOUR_API_KEY is the key that can be found on your API account page.

 

Đây là API Key mẫu mà trang cung cấp: i6j-HvYY6XXGSqzjkZycyEyLZbCDWAEX, bạn có thể sử dụng tuỳ ý hoặc tự get một API key khác.

 

Theo lưu ý chỗ in đậm: Phải chuyển cái API-Key sang Base64 mới sử dụng cho request được → Ta dùng hàm _B64Encode để chuyển.

 

 

- Tiếp theo ta xem Example cách upload ảnh mà trang https://tinypng.com cung cấp:

 

Example upload from URL

You can also provide a URL to your image instead of having to upload it. The API accepts a JSON body with the image URL as a source location.

 

POST /shrink HTTP/1.1

Host: api.tinify.com

Authorization: Basic YXBpOmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6MDEyMzQ1

Content-Type: application/json

 

{

 "source": {

   "url": "https://tinypng.com/images/panda-happy.png"

 }

}

 

 

 

#include <_HttpRequest.au3>

$API_Key = 'i6j-HvYY6XXGSqzjkZycyEyLZbCDWAEX'

$API_Key_B64 = _B64Encode(StringToBinary($API_Key))

$rq = _HttpRequest(1, 'https://api.tinify.com/shrink', '{"source": {"url": "https://cdn.tinypng.com/images/panda-happy.png"}}', '', '', 'Authorization: BASIC ' & $API_Key_B64)

MsgBox(4096, 'Kết quả', $rq)

 

Xem thêm các hàm _B64Encode, _GetFileInfo nếu chưa hiểu ví dụ.