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

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

Introduction

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

Prototype

public void setHeader(String header, String value) 

Source Link

Document

Sets a request header with the given name and value.

Usage

From source file:n3phele.client.view.NewUserView.java

License:Open Source License

private void createUser(String url, final String email, String firstName, String lastName, String password,
        String ec2Id, String ec2Secret) {

    // Send request to server and catch any errors.
    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    builder.setUser("signup");
    builder.setPassword("newuser");
    builder.setHeader("Content-type", "application/x-www-form-urlencoded");
    StringBuilder args = new StringBuilder();
    args.append("email=");
    args.append(URL.encodeQueryString(email));
    args.append("&firstName=");
    args.append(URL.encodeQueryString(firstName));
    args.append("&lastName=");
    args.append(URL.encodeQueryString(lastName));
    if (password != null && password.length() > 0) {
        args.append("&secret=");
        args.append(URL.encodeQueryString(password));
    }//w  w  w  .j ava  2  s .  c o m
    if (ec2Id != null && ec2Id.length() != 0) {
        args.append("&ec2Id=");
        args.append(URL.encodeQueryString(ec2Id));
        args.append("&ec2Secret=");
        args.append(URL.encodeQueryString(ec2Secret));
    }
    try {
        @SuppressWarnings("unused")
        Request request = builder.sendRequest(args.toString(), new RequestCallback() {
            public void onError(Request request, Throwable exception) {
                Window.alert("User create error " + exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                GWT.log("Got reply");
                if (201 == response.getStatusCode()) {
                    Window.alert("User " + email + " created.");
                } else {
                    Window.alert("User create failure " + response.getStatusText() + "\n" + response.getText());
                }
            }

        });
    } catch (RequestException e) {
        Window.alert("Account create exception " + e.getMessage());
    }
}

From source file:name.cphillipson.experimental.gwt.client.module.common.widget.suggest.MultivalueSuggestBox.java

License:Apache License

/**
 * Retrieve Options (name-value pairs) that are suggested from the REST endpoint
 * // w  w w  . j av a  2 s  .  co  m
 * @param query
 *            - the String search term
 * @param from
 *            - the 0-based begin index int
 * @param to
 *            - the end index inclusive int
 * @param callback
 *            - the OptionQueryCallback to handle the response
 */
private void queryOptions(final String query, final int from, final int to,
        final OptionQueryCallback callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            URL.encode(m_restEndpointUrl + "?q=" + query + "&indexFrom=" + from + "&indexTo=" + to));

    // Set our headers
    builder.setHeader("Accept", "application/json");
    builder.setHeader("Accept-Charset", "UTF-8");

    builder.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {
            final JSONValue val = JSONParser.parse(response.getText());
            final JSONObject obj = val.isObject();
            final int totSize = (int) obj.get(OptionResultSet.TOTAL_SIZE).isNumber().doubleValue();
            final OptionResultSet options = new OptionResultSet(totSize);
            final JSONArray optionsArray = obj.get(OptionResultSet.OPTIONS).isArray();

            if (options.getTotalSize() > 0 && optionsArray != null) {

                for (int i = 0; i < optionsArray.size(); i++) {
                    if (optionsArray.get(i) == null) {
                        /*
                         * This happens when a JSON array has an invalid trailing comma
                         */
                        continue;
                    }

                    final JSONObject jsonOpt = optionsArray.get(i).isObject();
                    final Option option = new Option();
                    option.setName(jsonOpt.get(OptionResultSet.DISPLAY_NAME).isString().stringValue());
                    option.setValue(jsonOpt.get(OptionResultSet.VALUE).isString().stringValue());
                    options.addOption(option);
                }
            }
            callback.success(options);
        }

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

    try {
        builder.send();
    } catch (final RequestException e) {
        updateFormFeedback(FormFeedback.ERROR, "Error: " + e.getMessage());
    }
}

From source file:net.ffxml.gwt.json.client.JsonRpc.java

License:Apache License

/**
 * Executes a json-rpc request.//from   w w w .  j av  a2s . co m
 * 
 * @param url
 *            The location of the service
 * @param username
 *            The username for basic authentification
 * @param password
 *            The password for basic authentification
 * @param method
 *            The method name
 * @param params
 *            An array of objects containing the parameters
 * @param callback
 *            A callbackhandler like in gwt's rpc.
 */
public void request(final String url, String username, String password, final String method, Object[] params,
        final AsyncCallback callback) {

    HashMap request = new HashMap();
    request.put("method", method);
    if (params == null) {
        params = new Object[] {};
    }
    request.put("params", params);
    request.put("id", new Integer(requestSerial++));

    if (username == null)
        if (requestUser != null)
            username = requestUser;
    if (password == null)
        if (requestPassword != null)
            password = requestPassword;

    RequestCallback handler = new RequestCallback() {
        public void onResponseReceived(Request request, Response response) {
            try {
                String resp = response.getText();
                if (resp.equals(""))
                    throw new RuntimeException("empty");
                HashMap reply = (HashMap) decode(resp);

                if (reply == null) {
                    RuntimeException runtimeException = new RuntimeException("parse: " + response.getText());
                    fireFailure(runtimeException);
                    callback.onFailure(runtimeException);
                }

                if (isErrorResponse(reply)) {
                    RuntimeException runtimeException = new RuntimeException("error: " + reply.get("error"));
                    fireFailure(runtimeException);
                    callback.onFailure(runtimeException);
                } else if (isSuccessfulResponse(reply)) {
                    callback.onSuccess(reply.get("result"));
                } else {
                    RuntimeException runtimeException = new RuntimeException("syntax: " + response.getText());
                    fireFailure(runtimeException);
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                fireFailure(e);
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter();
            }
        }

        public void onError(Request request, Throwable exception) {
            try {
                if (exception instanceof RequestTimeoutException) {
                    RuntimeException runtimeException = new RuntimeException("timeout");
                    fireFailure(runtimeException);
                    callback.onFailure(runtimeException);
                } else {
                    RuntimeException runtimeException = new RuntimeException("other");
                    fireFailure(runtimeException);
                    callback.onFailure(runtimeException);
                }
            } catch (RuntimeException e) {
                fireFailure(e);
                callback.onFailure(e);
            } finally {
                decreaseRequestCounter();
            }
        }

        private boolean isErrorResponse(HashMap response) {
            return response.get("error") != null && response.get("result") == null;
        }

        private boolean isSuccessfulResponse(HashMap response) {
            return response.get("error") == null && response.containsKey("result");
        }
    };

    increaseRequestCounter();

    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
    if (requestTimeout > 0)
        builder.setTimeoutMillis(requestTimeout);
    builder.setHeader("Content-Type", "application/json; charset=utf-8");
    String body = new String(encode(request));
    builder.setHeader("Content-Length", Integer.toString(body.length()));
    if (requestCookie != null)
        if (Cookies.getCookie(requestCookie) != null)
            builder.setHeader("X-Cookie", Cookies.getCookie(requestCookie));
    if (username != null)
        builder.setUser(username);
    if (password != null)
        builder.setPassword(password);
    try {
        builder.sendRequest(body, handler);
    } catch (RequestException exception) {
        handler.onError(null, exception);
    }
}

From source file:next.celebs.api.HTTP.java

License:Apache License

public static void doPost(String url, String postData, ResponseReader reader) {

    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
    builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
    try {//from   w  ww.  jav  a2  s.  com
        builder.sendRequest(postData, new Callback_(reader));
    } catch (RequestException e) {
        reader.onError(null, e);
    }
}

From source file:next.celebs.api.HTTP.java

License:Apache License

public static void doPostJSON(String url, String jsonData, ResponseReader reader) {

    RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL.encode(url));
    builder.setHeader("Content-Type", "application/json");
    try {/*ww  w  .ja va  2s.com*/
        builder.sendRequest(jsonData, new Callback_(reader));
    } catch (RequestException e) {
        reader.onError(null, e);
    }
}

From source file:next.celebs.api.HTTP.java

License:Apache License

public static void doDeleteJSON(String url, String jsonData, ResponseReader reader) {
    RequestBuilder builder = new RequestBuilder(RequestBuilder.DELETE, URL.encode(url));
    builder.setHeader("Content-Type", "application/json");
    try {/*from  ww w  .  j av a 2 s  .  com*/
        builder.sendRequest(jsonData, new Callback_(reader));
    } catch (RequestException e) {
        reader.onError(null, e);
    }
}

From source file:next.celebs.api.HTTP.java

License:Apache License

public static void doPut(String url, String postData, ResponseReader reader) {

    RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, URL.encode(url));
    builder.setHeader("Content-Type", "application/x-www-form-urlencoded");
    try {/*from   w w  w . ja  v a2  s.com*/
        builder.sendRequest(postData, new Callback_(reader));
    } catch (RequestException e) {
        reader.onError(null, e);
    }
}

From source file:next.celebs.api.HTTP.java

License:Apache License

public static void doPutJSON(String url, String jsonData, ResponseReader reader) {

    RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, URL.encode(url));
    builder.setHeader("Content-Type", "application/json");
    try {/*from   w ww . j  a  v  a2s  .co m*/
        builder.sendRequest(jsonData, new Callback_(reader));
    } catch (RequestException e) {
        reader.onError(null, e);
    }
}

From source file:nl.fontys.fhict.jea.gwt.jee7.client.bus.impl.connection.poll.PollConnection.java

private void connect() throws ConnectionException {
    RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, createURL());
    requestBuilder.setTimeoutMillis(0);//from w ww.  java 2s.  co  m
    requestBuilder.setHeader("Accept", BusService.MIME_TYPE_GWT_RPC);
    try {
        requestBuilder.sendRequest("", this);
        alive = true;
    } catch (RequestException ex) {
        throw new ConnectionException(ex);
    }
}

From source file:nl.mpi.tg.eg.experiment.client.service.DataSubmissionService.java

License:Open Source License

private void submitData(final ServiceEndpoint endpoint, final UserId userId, final String jsonData,
        final DataSubmissionListener dataSubmissionListener) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
            serviceLocations.dataSubmitUrl() + endpoint.name());
    builder.setHeader("Content-type", "application/json");
    RequestCallback requestCallback = new RequestCallback() {

        @Override//from  ww  w.  j a va 2 s  . c o m
        public void onError(Request request, Throwable exception) {
            logger.warning(builder.getUrl());
            logger.log(Level.WARNING, "RequestCallback", exception);
            dataSubmissionListener.scoreSubmissionFailed(new DataSubmissionException(
                    DataSubmissionException.ErrorType.connectionerror, endpoint.name()));
        }

        @Override
        public void onResponseReceived(Request request, Response response) {
            final JsArray<DataSubmissionResult> sumbmissionResult = JsonUtils
                    .<JsArray<DataSubmissionResult>>safeEval("[" + response.getText() + "]");
            // here we also check that the JSON return value contains the correct user id, to test for cases where a web cashe or wifi login redirect returns stale data or a 200 code for a wifi login
            if (200 == response.getStatusCode() && sumbmissionResult.length() > 0
                    && sumbmissionResult.get(0).getSuccess()
                    && userId.toString().equals(sumbmissionResult.get(0).getUserId())) {
                final String text = response.getText();
                logger.info(text);
                //                    localStorage.stowSentData(userId, jsonData);
                dataSubmissionListener.scoreSubmissionComplete(sumbmissionResult);
            } else {
                logger.warning(builder.getUrl());
                logger.warning(response.getStatusText());
                if (sumbmissionResult.length() > 0) {
                    dataSubmissionListener.scoreSubmissionFailed(
                            new DataSubmissionException(DataSubmissionException.ErrorType.dataRejected,
                                    sumbmissionResult.get(0).getMessage()));
                } else {
                    dataSubmissionListener.scoreSubmissionFailed(new DataSubmissionException(
                            DataSubmissionException.ErrorType.non202response, endpoint.name()));
                }
            }
        }
    };
    try {
        // todo: add the application build number to the submitted data
        builder.sendRequest(jsonData, requestCallback);
    } catch (RequestException exception) {
        logger.log(Level.SEVERE, "submit data failed", exception);
        dataSubmissionListener.scoreSubmissionFailed(
                new DataSubmissionException(DataSubmissionException.ErrorType.buildererror, endpoint.name()));
    }
}