Last active
February 8, 2023 16:11
-
-
Save faveoled/ce101404dfd8288245a7e2b93d5d2b18 to your computer and use it in GitHub Desktop.
J2CL http request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import elemental2.dom.XMLHttpRequest; | |
| import elemental2.promise.Promise; | |
| public class Http { | |
| enum HttpMethod { | |
| GET, POST | |
| } | |
| public static Promise<String> request(HttpMethod method, String url) { | |
| return new Promise<>((resolve, reject) -> { | |
| XMLHttpRequest xhr = new XMLHttpRequest(); | |
| xhr.onreadystatechange = e -> { | |
| if (xhr.readyState == XMLHttpRequest.DONE) { | |
| resolve.onInvoke(xhr.responseText); | |
| } | |
| return null; | |
| }; | |
| xhr.addEventListener("error", /*NON-NLS*/ (e) -> { | |
| reject.onInvoke(xhr.statusText); | |
| }); | |
| xhr.open(method.name(), url, true); | |
| xhr.send(); | |
| }); | |
| } | |
| } | |
| Promise<String> promise = Http.request( | |
| Http.HttpMethod.GET, | |
| "https://api.github.com" | |
| ); | |
| promise.then( | |
| success -> { | |
| DomGlobal.alert("success: \n" + success); | |
| return null; | |
| }, | |
| error -> { | |
| DomGlobal.alert("error: " + error); | |
| return null; | |
| } | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment