【问题标题】:cross domain requests with GWT使用 GWT 的跨域请求
【发布时间】:2012-03-03 16:45:28
【问题描述】:

尝试使用 GWT 应用程序发出跨域请求时在 chrome 上出现此错误。

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

我已尝试使用以下代码发送 GET 请求。

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

【问题讨论】:

  • 很遗憾,由于安全限制,这是不允许的
  • 是否有任何技巧/黑客可用于此
  • 我不知道。我们最终编写了一个运行在 GWT 应用程序后端并充当代理的小 servlet 或 jsp。它正在运行实际的 Java,因此它可以发出任何它想要的请求,适当地传递 GET/POST 参数,获取响应,将其发送回 GWT 客户端。很抱歉我不能分享代码,但它属于我的雇主。
  • 没关系,实际上我也用实际的 java 做过这件事,但不能用 GWT 做。所以,我想你可以告诉我你是如何在 servlet 中使用实际的 java 的。

标签: java gwt get request response


【解决方案1】:

使用JSONP 处理跨域请求。 (但存在一些限制 - 您只能使用 GET 方法)

另一种方法是使用 GWT 的 servlet 获取请求结果并将其返回给客户端。 iframe 也存在一些 hack,html5 也可以进行跨域请求。

【讨论】:

  • 我在 GWT 的 servlet 中尝试了同样的方法,但它总是抛出诸如 Source Not Found For Type 之类的异常。我也尝试过 GWTQuery,但仍然无法正确实现它。您对互联网上可用的任何工作示例有任何想法吗?谢谢
【解决方案2】:

我解决了这个问题并提出了这个可行的解决方案。 :)

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();
}

【讨论】:

    【解决方案3】:

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 2013-04-12
      • 2016-03-15
      • 2018-04-23
      • 2011-11-30
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-15
      相关资源
      最近更新 更多