Skip to content

Instantly share code, notes, and snippets.

@korzha
Created September 9, 2016 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korzha/e0fa128bdf8e92e1f77832b04263c486 to your computer and use it in GitHub Desktop.
Save korzha/e0fa128bdf8e92e1f77832b04263c486 to your computer and use it in GitHub Desktop.
public static CompletableFuture<String> getUrlBytes(String url) {
CompletableFuture<String> future = new CompletableFuture<>();
final XMLHttpRequest req = new XMLHttpRequest();
req.open("GET", url, true);
req.setOnreadystatechange((e) -> {
if (req.status == 200) {
future.complete(req.response);
} else {
future.completeExceptionally(new Exception(req.statusText));
}
});
req.onerror = function() {
future.completeExceptionally(new Exception("Network Error"));
};
req.send();
return future;
}
@JsType( isNative = true, namespace = JsPackage.GLOBAL, name = "XMLHttpRequest" )
public class XMLHttpRequest
{
@JsMethod
public native void open( String method, String url, boolean isAsync );
@JsMethod
public native void send( Object data );
@JsProperty
public native void setOnreadystatechange( ReadyStateHandler handler );
@JsMethod
public native void setRequestHeader( String headerName, String value );
@JsProperty
public native int getReadyState();
@JsProperty
public native int getStatus();
@JsProperty
public native String getResponseText();
}
@JsFunction
@FunctionalInterface
public interface ReadyStateHandler
{
void onStateChanged( Object event );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment