GWT - How to return a String value from RequestBui

2019-07-25 15:10发布

I'm unable to figure out how to return a String value from RequestBuilder's sendRequest() method after receiving a response. I referred to a similar question where the suggestion was to use Callback<String, String> callback but I can't figure out how to implement this. The GWT documentation for Callback does not have any examples.

What I have is a class Requester with the method generateRequest() that should make a request with RequestBuilder and return a String when called. The processResponse() method takes the response, parses it and returns a String which I'm storing in output. How can I return this output String when generateRequest() is called from another class?

public String generateRequest() {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, URL.encode(url.getUrl()));
        builder.setHeader("Authorization", authHeader);
        String title = null;

        try {
            builder.sendRequest(null, new RequestCallback() {

                public void onError(Request request, Throwable exception) {
                    GWT.log(exception.getMessage());
                }

                public void onResponseReceived(Request request, Response response) {
                    String output = processResponse(response);
                }
            });
        } catch (RequestException e) {
            GWT.log(e.getMessage());
        }

    return title;
}

2条回答
对你真心纯属浪费
2楼-- · 2019-07-25 15:54

I think you might be misunderstanding something.

You cannot simply return a String because the call is async (i.e. you can't return the String because the String is simply not available yet, at the time you wish to return it). You could simply wait there until the call result is ready, but this is really terrible practice; that's why you're seeing people suggesting callbacks.

查看更多
不美不萌又怎样
3楼-- · 2019-07-25 16:07

Imagine, this is the code:

statement01;
statement02;
String result = generateRequest(...);
statement04UsingResult;
statement05;

then this will not work, because result will not be available before statement04UsingResult is executed. The Request has not finished yet. (as Andrej already mentioned)

To solve this, split your code:

statement01;
statement02;
generateRequest(...);

create an new void method, wich accepts the result as parameter:

public void newMethod(String result) {
    statement04UsingResult;
    statement05;
}

and call from inside the onResponseRevieve-method:

           builder.sendRequest(null, new RequestCallback() {

            public void onError(Request request, Throwable exception) {
                GWT.log(exception.getMessage());
            }

            public void onResponseReceived(Request request, Response response) {
                newMethod(processResponse(response));
            }
        });

Hope that helps.

查看更多
登录 后发表回答