// // Copyright 2015-2021 by Garmin Ltd. or its subsidiaries. // Subject to Garmin SDK License Agreement and Wearables // Application Developer Agreement. // import Toybox.Communications; import Toybox.Cryptography; import Toybox.Lang; import Toybox.Time.Gregorian; using Toybox.PersistedContent; class Http { var host; var uri; var caller; var cb; var body; var html_opts as Dictionary or Null; public function initialize(host) { me.host = ((host == null) || host.equals("")) ? null : proto(host); set_opts({"Content-Type" => Communications.REQUEST_CONTENT_TYPE_JSON}, Communications.HTTP_RESPONSE_CONTENT_TYPE_JSON); } function set_opts(hdrs as Dictionary, reply) { html_opts = { :headers => hdrs, :responseType => reply }; } public function get_host() { return host; } public function set_host(host) { me.host = host; } private function proto(h) { if (h == null) { return h; } if (h.find("?") == 0) { return null; } if (h.find("://") != null) { return h; } return "https://" + h; } public function get(uri, body, caller, cb) { return do_req(Communications.HTTP_REQUEST_METHOD_GET, uri, body, caller, cb); } public function post(uri, body, caller, cb) { return do_req(Communications.HTTP_REQUEST_METHOD_POST, uri, body, caller, cb); } public function do_req(type, uri, body, caller, cb) { if (host == null || host.length() == 0) { //C.set_alert(null, "No host"); return; } me.uri = uri; me.body = body; me.caller = caller; me.cb = cb; html_opts[:method] = type; //L.dbg_log(L.DBG_HTTP, "do_req(" + type + "):" + host + uri + " => " + body); Communications.makeWebRequest( host + uri, body, html_opts, method(:got_req) ); return; } //! Receive the data from the initial API request public function got_req(responseCode as Number, data as Dictionary or PersistedContent.Iterator or String or Null) as Void { //L.pr_json(L.DBG_HTTP, "got_req:" + responseCode, data); cb.invoke(responseCode, data, caller); } }