Saurabh Saxena
Saurabh Saxena

Reputation: 3205

cross domain requests with GWT

Getting this error on chrome while trying to make cross-domain requests with GWT application.

Origin http://127.0.0.1:8888 is not allowed by Access-Control-Allow-Origin.

I have tried the following code for sending GET request.

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;

import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;


public class Detracker implements EntryPoint {
    public void onModuleLoad() {
        doGet("http://www.google.com");
    }

    public static void doGet(String url) {
        RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

        try {
            builder.sendRequest(null, new RequestCallback() {
                public void onError(Request request, Throwable exception) {
                    // Code omitted for clarity
                }

                @Override
                public void onResponseReceived(Request request,
                        Response response) {
                    final Label msgLabel = new Label();
                    msgLabel.setText(response.getText());
                    RootPanel.get("resultContainer").add(msgLabel);
                }
            });

        } catch (RequestException e) {
            // Code omitted for clarity
        }
    }
}

Upvotes: 1

Views: 3554

Answers (3)

Blessed Geek
Blessed Geek

Reputation: 21614

See HITCH HIKER'S GUIDE TO JAVA

Upvotes: 0

Saurabh Saxena
Saurabh Saxena

Reputation: 3205

I worked around and came out with this working solution. :)

String message = "";


try {
    URL url = new URL("working-url");
    URLConnection urlConn = url.openConnection();
    urlConn.setReadTimeout(100000);
    BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    String line;

    while ((line = reader.readLine()) != null) {
        message = message.concat(line);
    }
    reader.close();

} catch (MalformedURLException e) {
message = e.getMessage();
} catch (IOException e) {
message = e.getMessage();
}

Upvotes: 1

WelcomeTo
WelcomeTo

Reputation: 20571

Use JSONP for crossdomain requests. (But there exist some restrictions - you can only GET method)

Another way is to use GWT's servlet to get result of request and return it to client. Also exist some hacks with iframe, html5 also can make crossdomain requests.

Upvotes: 2

Related Questions