2012-03-03 220 views
1

在尝试使用GWT应用程序进行跨域请求时在chrome上获取此错误。使用GWT跨域请求

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

它是不允许的,不幸的是,由于安全限制 – dldnh 2012-03-03 16:51:50

+0

没有任何诀窍/黑客可用于此 – 2012-03-03 16:56:21

+2

不是我所知道的。我们最终编写了一个运行在我们GWT应用后端的小servlet或jsp,并充当代理的一部分。它运行的是真正的Java,所以它可以发出任何想要的请求,根据需要传递GET/POST参数,获取响应,并将其发送回GWT客户端。对不起,我不能分享代码,但它属于我的雇主。 – dldnh 2012-03-03 17:33:25

回答

1

我工作围绕与此的工作解决方案就出来了。 :)

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

对于跨域请求使用JSONP。 (但是存在一些限制 - 只能使用GET方法)

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

+0

我试图从GWT的servlet相同,但它总是抛出异常,如类似的来源未找到。我也尝试GWTQuery,但仍然无法正确实现它。你有任何关于互联网上可用的工作示例的想法。 谢谢 – 2012-03-04 18:17:56