Example usage for com.google.gwt.http.client RequestBuilder GET

List of usage examples for com.google.gwt.http.client RequestBuilder GET

Introduction

In this page you can find the example usage for com.google.gwt.http.client RequestBuilder GET.

Prototype

Method GET

To view the source code for com.google.gwt.http.client RequestBuilder GET.

Click Source Link

Document

Specifies that the HTTP GET method should be used.

Usage

From source file:com.google.gwt.sample.healthyeatingapp.client.FacebookGraph.java

public void RequestAuthorizationAndQueryGraph(final String id, final Callback<JSONObject, Throwable> callback) {
    RequestAuthorizationAndQueryGraph(id, RequestBuilder.GET, null, callback);
}

From source file:com.google.gwt.sample.healthyeatingapp.client.FacebookGraph.java

private void QueryGraph(String id, Method method, String params,
        final Callback<JSONObject, Throwable> callback) {
    final String requestData = "access_token=" + token + (params != null ? "&" + params : "");
    RequestBuilder builder;/*from   w w w . j a v a2s  .c o  m*/
    if (method == RequestBuilder.POST) {
        builder = new RequestBuilder(method, "https://graph.facebook.com/" + id);
        builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
    } else if (method == RequestBuilder.GET) {
        builder = new RequestBuilder(method, "https://graph.facebook.com/" + id + "?" + requestData);
    } else {
        callback.onFailure(new IOException("doGraph only supports GET and POST requests"));
        return;
    }
    try {
        builder.sendRequest(requestData, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                callback.onFailure(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                if (Response.SC_OK == response.getStatusCode()) {
                    callback.onSuccess(JSONParser.parseStrict(response.getText()).isObject());
                } else if (Response.SC_BAD_REQUEST == response.getStatusCode()) {
                    callback.onFailure(new IOException("Error: " + response.getText()));
                } else {
                    callback.onFailure(
                            new IOException("Couldn't retrieve JSON (" + response.getStatusText() + ")"));
                }
            }

        });
    } catch (RequestException e) {
        callback.onFailure(e);
    }
}

From source file:com.google.gwt.sample.showcase.client.ContentWidget.java

License:Apache License

/**
 * Send a request for source code.//  w ww.j  a va  2  s.  com
 * 
 * @param callback the {@link RequestCallback} to send
 * @param url the URL to target
 */
private void sendSourceRequest(RequestCallback callback, String url) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, GWT.getModuleBaseURL() + url);
    builder.setCallback(callback);
    try {
        builder.send();
    } catch (RequestException e) {
        callback.onError(null, e);
    }
}

From source file:com.google.gwt.sample.simplexml.client.SimpleXML.java

License:Apache License

public void onModuleLoad() {
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "customerRecord.xml");

    try {//  w  ww .j a va 2s .c  om
        requestBuilder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                requestFailed(exception);
            }

            public void onResponseReceived(Request request, Response response) {
                renderXML(response.getText());
            }
        });
    } catch (RequestException ex) {
        requestFailed(ex);
    }
}

From source file:com.google.gwt.sample.stockwatcher.client.PetrolTracker.java

/**
 * Add stock to FlexTable. Executed when the user clicks the addStockButton or
 * presses enter in the newSymbolTextBox.
         /*from   w  ww .  j av  a  2 s .c  o m*/
private void addFillups() {
  final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
  newSymbolTextBox.setFocus(true);
        
  // Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
  if (!symbol.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
    Window.alert("'" + symbol + "' is not a valid symbol.");
    newSymbolTextBox.selectAll();
    return;
  }
        
  newSymbolTextBox.setText("");
        
  // Don't add the stock if it's already in the table.
  if (stocks.contains(symbol))
    return;
        
  // Add the stock to the table.
  int row = fillupFlexTable.getRowCount();
  stocks.add(symbol);
  fillupFlexTable.setText(row, 0, symbol);
  fillupFlexTable.setWidget(row, 2, new Label());
  fillupFlexTable.getCellFormatter().addStyleName(row, 1, "watchListNumericColumn");
  fillupFlexTable.getCellFormatter().addStyleName(row, 2, "watchListNumericColumn");
  fillupFlexTable.getCellFormatter().addStyleName(row, 3, "watchListRemoveColumn");
        
  // Add a button to remove this stock from the table.
  Button removeStockButton = new Button("x");
  removeStockButton.addStyleDependentName("remove");
  removeStockButton.addClickHandler(new ClickHandler() {
    public void onClick(ClickEvent event) {
int removedIndex = stocks.indexOf(symbol);
stocks.remove(removedIndex);
fillupFlexTable.removeRow(removedIndex + 1);
    }
  });
  fillupFlexTable.setWidget(row, 3, removeStockButton);
        
  // Get the stock price.
  refreshWatchList();
        
}
*/
private void refreshFillups() {
    String url = JSON_URL;

    final String encodedUrl = URL.encode(url);
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, encodedUrl);
    try {
        @SuppressWarnings("unused")
        Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON on url:" + encodedUrl);
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    String jsonString = response.getText();
                    updateTable(asArrayOfFillupData(jsonString));
                } else {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }
        });
    } catch (RequestException e) {
        displayError("Couldn't retrieve JSON");
    }

}

From source file:com.google.gwt.sample.stockwatcher.client.ui.StockWatcherViewImpl.java

/**
 * Generate random stock prices./*from w  w w  .j  a v  a 2 s. com*/
 */
private void refreshWatchList() {
    if (stocks.size() == 0) {
        return;
    }
    String url = JSON_URL;

    // Append watch list stock symbols to query URL.
    Iterator iter = stocks.iterator();
    while (iter.hasNext()) {
        url += iter.next();
        if (iter.hasNext()) {
            url += "+";
        }
    }

    url = URL.encode(url);

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
        Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    updateTable(asArrayOfStockData(response.getText()));
                } else {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }
        });
    } catch (RequestException e) {
        displayError("Couldn't retrieve JSON");
    }
}

From source file:com.google.gwt.sample.stockwatcher_json.client.StockWatcherJSON.java

private void randomizeNumber() {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, JSON_RANDOMIZE);

    try {//from  w  w w.j  a  va  2  s.com
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON : " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    StockWatcherJSON.this.randomizeLabel.setText(response.getText());
                    StockWatcherJSON.this.randomizeLabel.setVisible(true);
                } else {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                    StockWatcherJSON.this.randomizeLabel.setVisible(false);
                }
            }
        });
    } catch (RequestException e) {
        displayError("Couldn't retrieve JSON : " + e.getMessage());
        StockWatcherJSON.this.randomizeLabel.setVisible(false);
    }
}

From source file:com.google.gwt.sample.stockwatcher_json.client.StockWatcherJSON.java

private void refreshWatchList() {
    if (stocks.size() == 0) {
        return;//from w  w w  .  j a va 2 s.  com
    }

    String url = JSON_STOCK_PRICES_URL;

    // Append watch list stock symbols to query URL.
    Iterator<String> iter = stocks.iterator();
    while (iter.hasNext()) {
        url += iter.next();
        if (iter.hasNext()) {
            url += "+";
        }
    }

    url = URL.encode(url);
    GWT.log("url = " + url);
    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
        builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON : " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    updateTable(asArrayOfStockData(response.getText()));
                } else {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }
        });
    } catch (RequestException e) {
        displayError("Couldn't retrieve JSON : " + e.getMessage());
    }
}

From source file:com.google.gwt.sample.userwatcher.client.PageWithoutPhoto.java

private void refreshWatchList() {

    if (stocks.size() == 0) {
        return;/*w ww .ja  v a  2 s.  com*/
    }

    String url = JSON_URL;

    // Append watch list stock symbols to query URL.
    Iterator<String> iter = stocks.iterator();
    while (iter.hasNext()) {
        url += iter.next();
        if (iter.hasNext()) {
            url += "+";
        }
    }

    url = URL.encode(url);

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

    try {
        Request request = builder.sendRequest(null, new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                displayError("Couldn't retrieve JSON");
            }

            public void onResponseReceived(Request request, Response response) {
                if (200 == response.getStatusCode()) {
                    updateTable(JsonUtils.<JsArray<StockData>>safeEval(response.getText()));
                } else {
                    displayError("Couldn't retrieve JSON (" + response.getStatusText() + ")");
                }
            }
        });
    } catch (RequestException e) {
        displayError("Couldn't retrieve JSON");
    }

}

From source file:com.google.walkaround.wave.client.rpc.AjaxRpc.java

License:Open Source License

@Override
public RpcHandle makeRequest(Method method, String serviceName, ReadableStringMap<String> params,
        final Rpc.RpcCallback rpcCallback) {

    final int requestId = nextRequestId;
    nextRequestId++;//from  w  w w .jav a2  s.c o m

    // See the javadoc for HARD_RELOAD.
    if (connectionState == ConnectionState.HARD_RELOAD) {
        return new Handle(requestId);
    }

    final String requestData;
    final RequestBuilder.Method httpMethod;

    StringBuilder urlBuilder = new StringBuilder(rpcRoot + "/" + serviceName + "?");
    // NOTE(danilatos): For some reason, IE6 seems not to perform some requests
    // it's already made, resulting in... no data. Inserting some
    // unique value into the request seems to fix that.
    if (UserAgent.isIE()) {
        urlBuilder.append("_no_cache=" + requestId + "" + Duration.currentTimeMillis() + "&");
    }

    if (method == Method.GET) {
        httpMethod = RequestBuilder.GET;
        addParams(urlBuilder, params);
        requestData = "";
    } else {
        httpMethod = RequestBuilder.POST;
        requestData = addParams(new StringBuilder(), params).toString();
    }

    final String url = urlBuilder.toString();

    RequestBuilder r = new RequestBuilder(httpMethod, url);
    if (method == Method.POST) {
        r.setHeader("Content-Type", "application/x-www-form-urlencoded");
        r.setHeader("X-Same-Domain", "true");
    }

    log.log(Level.INFO, "RPC Request, id=", requestId, " method=", httpMethod, " urlSize=", url.length(),
            " bodySize=", requestData.length());

    class RpcRequestCallback implements RequestCallback {
        @Override
        public void onResponseReceived(Request request, Response response) {
            RpcHandle handle = handles.get(requestId);
            if (handle == null) {
                // It's been dropped
                log.log(Level.INFO, "RPC SuccessDrop, id=", requestId);
                return;
            }

            // Clear it now, before callbacks
            removeHandle();

            int statusCode = response.getStatusCode();
            String data = response.getText();

            Result result;
            if (statusCode < 100) {
                result = Result.RETRYABLE_FAILURE;
                maybeSetConnectionState(ConnectionState.OFFLINE);
            } else if (statusCode == 200) {
                result = Result.OK;
                maybeSetConnectionState(ConnectionState.CONNECTED);
                consecutiveFailures = 0;
            } else if (statusCode >= 500) {
                result = Result.RETRYABLE_FAILURE;
                consecutiveFailures++;
                if (consecutiveFailures > MAX_CONSECUTIVE_FAILURES) {
                    maybeSetConnectionState(ConnectionState.OFFLINE);
                } else {
                    maybeSetConnectionState(ConnectionState.CONNECTED);
                }
            } else {
                result = Result.PERMANENT_FAILURE;
                maybeSetConnectionState(ConnectionState.SOFT_RELOAD);
            }

            switch (result) {
            case OK:
                log.log(Level.INFO, "RPC Success, id=", requestId);
                try {
                    rpcCallback.onSuccess(data);
                } catch (MessageException e) {
                    // Semi-HACK(danilatos): Treat parse errors as login problems
                    // due to loading a login or authorization page. (It's unlikely
                    // we'd otherwise get a parse error from a 200 OK result).
                    // The simpler solution of detecting redirects is not possible
                    // with XmlHttpRequest, the web is unfortunately broken.

                    // TODO(danilatos) Possible alternatives:
                    // either change our server side to not require
                    // login through web.xml but to check if UserService says currentUser==null (or
                    // whatever it does if not logged in) and return a well-defined "not logged in"
                    // response instead, or to prefix all responses from the server with a fixed string
                    // (like we do with "OK" elsewhere) and assume not logged in if that prefix is
                    // missing.  We could strip off that prefix here and make it transparent to the
                    // callbacks.

                    maybeSetConnectionState(ConnectionState.LOGGED_OUT);

                    error(new Exception("RPC failed due to message exception, treating as auth failure"
                            + ", status code: " + statusCode + ", data: " + data));
                }
                break;
            case RETRYABLE_FAILURE:
                error(new Exception("RPC failed, status code: " + statusCode + ", data: " + data));
                break;
            case PERMANENT_FAILURE:
                fatal(new Exception("RPC bad request, status code: " + statusCode + ", data: " + data));
                break;
            default:
                throw new AssertionError("Unknown result " + result);
            }
        }

        @Override
        public void onError(Request request, Throwable exception) {
            if (!handles.containsKey(requestId)) {
                log.log(Level.INFO, "RPC FailureDrop, id=", requestId, exception.getMessage());
                return;
            }
            removeHandle();
            error(exception);
        }

        private void fatal(Throwable e) {
            log.log(Level.WARNING, "RPC Bad Request, id=", requestId, e.getMessage(), "Request url:" + url, e);
            rpcCallback.onFatalError(e);
        }

        private void error(Throwable e) {
            log.log(Level.WARNING, "RPC Failure, id=", requestId, e.getMessage(), "Request url:" + url, e);
            rpcCallback.onConnectionError(e);
        }

        private void removeHandle() {
            handles.remove(requestId);
        }
    }

    RpcRequestCallback innerCallback = new RpcRequestCallback();

    try {
        // TODO: store the Request object somewhere so we can e.g. cancel it
        r.sendRequest(requestData, innerCallback);
        Handle handle = new Handle(requestId);
        handles.put(handle.getId(), handle);
        return handle;
    } catch (RequestException e) {
        // TODO(danilatos) Decide if this should be a badRequest.
        innerCallback.error(e);
        return null;
    }
}