Skip to content

Instantly share code, notes, and snippets.

@faveoled
Last active February 8, 2023 16:11
Show Gist options
  • Select an option

  • Save faveoled/ce101404dfd8288245a7e2b93d5d2b18 to your computer and use it in GitHub Desktop.

Select an option

Save faveoled/ce101404dfd8288245a7e2b93d5d2b18 to your computer and use it in GitHub Desktop.
J2CL http request
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