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

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

Introduction

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

Prototype

Method POST

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

Click Source Link

Document

Specifies that the HTTP POST method should be used.

Usage

From source file:com.fredhat.gwt.xmlrpc.client.XmlRpcClient.java

License:Open Source License

/**
 * Executes an asynchronous XMLRPC call to the server with a specified username
 * and password.  If the execution was successful, the callback's {@link AsyncCallback#onSuccess(Object)} 
 * method will be invoked with the return value as the argument.  If the 
 * execution failed for any reason, the callback's {@link AsyncCallback#onFailure(Throwable)} method will 
 * be invoked with an instance of {@link XmlRpcException} instance as it's argument.
 * @param username the username for authentication
 * @param password the password for authentication
 * @param methodName the name of the XMLRPC method
 * @param params the parameters for the XMLRPC method
 * @param callback the logic implementation for handling the XMLRPC responses.
 * @deprecated As of XMLRPC-GWT v1.1,/*  w  w  w .  java2 s.co  m*/
 * build an {@link XmlRpcRequest} then call {@link XmlRpcRequest#execute()}
 */
@SuppressWarnings("unchecked")
@Deprecated
public void execute(String username, String password, String methodName, Object[] params,
        final AsyncCallback callback) {
    if (methodName == null || methodName.equals("")) {
        callback.onFailure(new XmlRpcException("The method name parameter cannot be null"));
        return;
    }
    if (params == null)
        params = new Object[0];

    Document request = buildRequest(methodName, params);
    if (debugMessages)
        System.out.println("** Request **\n" + request + "\n*************");

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, serverURL);
    requestBuilder.setHeader("Content-Type", "text/xml");
    requestBuilder.setTimeoutMillis(timeout);
    if (username != null)
        requestBuilder.setUser(username);
    if (password != null)
        requestBuilder.setPassword(password);

    try {
        requestBuilder.sendRequest(request.toString(), new RequestCallback() {
            public void onResponseReceived(Request req, Response res) {
                if (res.getStatusCode() != 200) {
                    callback.onFailure(new XmlRpcException("Server returned " + "response code "
                            + res.getStatusCode() + " - " + res.getStatusText()));
                    return;
                }
                Object responseObj = buildResponse(res.getText());
                if (responseObj instanceof XmlRpcException)
                    callback.onFailure((XmlRpcException) responseObj);
                else
                    callback.onSuccess(responseObj);
            }

            public void onError(Request req, Throwable t) {
                callback.onFailure(t);
            }
        });
    } catch (RequestException e) {
        callback.onFailure(new XmlRpcException("Couldn't make server request", e));
    }
}

From source file:com.fredhat.gwt.xmlrpc.client.XmlRpcRequest.java

License:Open Source License

/**
 * Invokes the XML-RPC method asynchronously.  All success and failure logic will
 * be in your {@link AsyncCallback} that you defined in the constructor.
 *///w w  w  . ja v a  2s  .  co m
public void execute() {
    if (methodName == null || methodName.equals("")) {
        callback.onFailure(new XmlRpcException("The method name parameter cannot be null"));
        return;
    }

    if (params == null)
        params = new Object[] {};

    Document request = buildRequest(methodName, params);
    if (client.getDebugMode())
        System.out.println("** Request **\n" + request + "\n*************");

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, client.getServerURL());
    requestBuilder.setHeader("Content-Type", "text/xml");

    //Ak existuje cookie posli ju v hlavicke
    if (Cookies.getCookie("sessionID") != null) {
        requestBuilder.setHeader("sessionID", Cookies.getCookie("sessionID"));
    }

    requestBuilder.setTimeoutMillis(client.getTimeoutMillis());
    if (client.getUsername() != null)
        requestBuilder.setUser(client.getUsername());
    if (client.getPassword() != null)
        requestBuilder.setPassword(client.getPassword());

    try {

        requestBuilder.sendRequest(request.toString(), new RequestCallback() {
            public void onResponseReceived(Request req, Response res) {
                if (res.getStatusCode() != 200) {
                    callback.onFailure(new XmlRpcException("Server returned " + "response code "
                            + res.getStatusCode() + " - " + res.getStatusText()));
                    return;
                }
                try {
                    T responseObj = buildResponse(res.getText());
                    callback.onSuccess(responseObj);

                } catch (XmlRpcException e) {
                    callback.onFailure(e);
                } catch (ClassCastException e) {
                    callback.onFailure(e);
                }
            }

            public void onError(Request req, Throwable t) {
                callback.onFailure(t);
            }
        });
    } catch (RequestException e) {
        callback.onFailure(new XmlRpcException("Couldn't make server request.  Are you violating the "
                + "Same Origin Policy?  Error: " + e.getMessage(), e));
    }
}

From source file:com.github.tdesjardins.ol3.demo.client.example.WfsExample.java

License:Apache License

@Override
public void show(String exampleId) {

    // create a vector layer
    Vector vectorSource = new Vector();
    VectorLayerOptions vectorLayerOptions = new VectorLayerOptions();
    vectorLayerOptions.setSource(vectorSource);
    ol.layer.Vector wfsLayer = new ol.layer.Vector(vectorLayerOptions);

    // create a view
    View view = new View();

    Coordinate centerCoordinate = new Coordinate(-8908887.277395891, 5381918.072437216);
    view.setCenter(centerCoordinate);//from w  w  w.ja v  a 2  s .  c om
    view.setZoom(12);
    view.setMaxZoom(19);

    // create the map
    MapOptions mapOptions = OLFactory.createOptions();
    mapOptions.setTarget(exampleId);
    mapOptions.setView(view);

    Map map = new Map(mapOptions);

    map.addLayer(DemoUtils.createOsmLayer());
    map.addLayer(wfsLayer);

    Wfs wfs = new Wfs();
    WfsWriteFeatureOptions wfsWriteFeatureOptions = new WfsWriteFeatureOptions();

    String[] featureTypes = { "water_areas" };
    wfsWriteFeatureOptions.setSrsName(DemoConstants.EPSG_3857);
    wfsWriteFeatureOptions.setFeaturePrefix("osm");
    wfsWriteFeatureOptions.setFeatureNS("http://openstreemap.org");
    wfsWriteFeatureOptions.setFeatureTypes(featureTypes);

    // set a filter
    wfsWriteFeatureOptions.setFilter(new IsLike("name", "Mississippi*"));
    wfsWriteFeatureOptions.setOutputFormat("application/json");

    // create WFS-XML node
    Node wfsNode = wfs.writeGetFeature(wfsWriteFeatureOptions);

    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST,
            "https://ahocevar.com/geoserver/wfs");
    requestBuilder.setRequestData(new XMLSerializer().serializeToString(wfsNode));
    requestBuilder.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {

            GeoJson geoJson = new GeoJson();
            Feature[] features = geoJson.readFeatures(response.getText());

            vectorSource.addFeatures(features);
            map.getView().fit(vectorSource.getExtent());
        }

        @Override
        public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
            Window.alert(exception.getMessage());
        }

    });

    try {
        requestBuilder.send();
    } catch (RequestException e) {
        Window.alert(e.getMessage());
    }

}

From source file:com.gloopics.g3viewer.client.G3Viewer.java

License:Apache License

public void doJSONRequest(final String a_URL, final HttpSuccessHandler a_Handler, final boolean a_hasParams,
        final boolean a_IncludeCSRF, String a_Data) {
    try {/*  www .j  av  a2  s .  co m*/
        String url;
        if (m_CSRF != null && a_IncludeCSRF) {
            url = a_URL + (a_hasParams ? "&csrf=" : "?csrf=") + m_CSRF;
        } else {
            url = a_URL;
        }
        RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url);
        requestBuilder.setHeader("Content-Type", "application/x-www-form-urlencoded");
        requestBuilder.setHeader("X-Requested-With", "XMLHttpRequest");
        requestBuilder.setCallback(new JSONResponseTextHandler(new JSONResponseCallback() {

            @Override
            public void onResponse(JSONValue aValue) {
                a_Handler.success(aValue);
            }

            @Override
            public void onError(Throwable aThrowable) {

                if (aThrowable.getCause() != null) {
                    StringBuffer stack = new StringBuffer();
                    StackTraceElement[] stes = aThrowable.getCause().getStackTrace();
                    for (StackTraceElement ste : stes) {
                        stack.append(ste.toString());
                        stack.append(" \n ");
                    }
                    displayError("a Unexpected Error ",
                            aThrowable.toString() + " - " + a_URL + "\n " + stack.toString());

                } else {
                    displayError("a Unexpected Error ", aThrowable.toString() + " - " + a_URL);
                }
            }
        }));

        requestBuilder.setRequestData(a_Data);
        requestBuilder.send();
    } catch (RequestException ex) {
        displayError("Request Exception", ex.toString() + " - " + a_URL);
    }
}

From source file:com.goodow.wind.channel.rpc.impl.AjaxRpc.java

License:Apache License

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

    final int requestId = nextRequestId;
    nextRequestId++;/*from   w w w .  ja  va  2 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: 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 (!Browser.getInfo().isWebKit() && !Browser.getInfo().isGecko()) {
        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 onError(Request request, Throwable exception) {
            if (!handles.hasKey(requestId)) {
                log.log(Level.INFO, "RPC FailureDrop, id=" + requestId + " " + exception.getMessage());
                return;
            }
            removeHandle();
            error(exception);
        }

        @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 (JsonException e) {
                    // Semi-HACK: 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 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);
            }
        }

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

        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 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: Decide if this should be a badRequest.
        innerCallback.error(e);
        return null;
    }
}

From source file:com.google.code.gwt.rest.client.impl.RestClientBuilder.java

License:Apache License

public RestPathBinding<T, R> createPostRequest(String uriTemplate) {
    return new RestRequestClientImpl(uriTemplate, RequestBuilder.POST);
}

From source file:com.google.gwt.examples.http.client.PostExample.java

public static void doPost(String url, String postData) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);

    try {//from  w w  w.  j av  a  2 s.c o m
        builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
        Request response = builder.sendRequest(postData, new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                // code omitted for clarity
            }

            public void onResponseReceived(Request request, Response response) {
                // code omitted for clarity
            }
        });
    } catch (RequestException e) {
        Window.alert("Failed to send the request: " + e.getMessage());
    }
}

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;//w  w w .j a va 2  s .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.userwatcher.client.UploadImage.java

private void send() {
    cp.showLoading(true);/*from www .ja  v a  2  s. c o  m*/

    String boundary = createBoundary();

    String requestData = getRequestData(boundary);

    //System.out.println(requestData);
    //url = "/TestOut/";

    //Window.alert("requestData=" + requestData);
    RootPanel.get().add(new HTML("<br>requestData=" + requestData));

    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    builder.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    builder.setHeader("Content-Length", Long.toString(requestData.length()));
    try {
        builder.sendRequest(requestData, new RequestCallback() {
            public void onResponseReceived(Request request, Response response) {
                cp.showLoading(false);
                if (response.getStatusCode() == 200) {
                    processResponse(response);
                }
            }

            public void onError(Request request, Throwable exception) {
                fireChange(EventManager.FILE_DONEUPLOADING);
                cp.showLoading(false);
                exception.printStackTrace();
            }
        });
    } catch (RequestException e) {
        cp.showLoading(false);
        e.printStackTrace();
    }
}

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  .  j a va2s.  c  om*/

    // 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;
    }
}