我正在尝试从GWT应用程序客户端的php Web服务(已将其放入本地localhost-经过测试并且可以正常工作)获取数据。
我尝试使用以下软件包com.google.gwt.http.client.*
,看起来代码工作正常,但响应始终为0,这很可能是一个问题,但我仍然不知道如何解决即使我尝试使用requestBuilder.setHeader(..);
这是我正在处理的代码:
String url = "http://localhost/geoTrackerTest.php?id=15";
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, URL.encode(url));
requestBuilder.setHeader("Access-Control-Allow-Origin", "http://localhost");
requestBuilder.setHeader("Access-Control-Allow-Methods", "POST, GET, UPDATE, OPTIONS");
requestBuilder.setHeader("Access-Control-Allow-Headers", "x-http-method-override");
try {
Request request = requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
GWT.log("Error: "+exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
GWT.log("response: "+response.getText());
} else {
GWT.log("response code: "+response.getStatusCode());
}
}
});
} catch (RequestException e) {
GWT.log("Request Exception: "+e.getMessage());
}
我仍然收到0作为回应。
答案 0 :(得分:0)
您需要从服务器端(而不是GWT客户端)设置响应头,然后才能从GWT RequestBuilder发出跨站点请求。在服务器端是这样的:
Response.setHeader("Access-Control-Allow-Origin","http://localhost");
如果只需要发送GET请求,则可以使用JSONP(http://www.gwtproject.org/javadoc/latest/com/google/gwt/jsonp/client/JsonpRequestBuilder.html)来发送跨域请求,而无需在服务器端设置标头。