2012-03-03 126 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