我有一个GWT应用程序,我希望以jSON格式从endomondo获取数据,我可以通过以下IRL获得它:
http://api.mobile.endomondo.com/mobile/api/workout/list?authToken=XXXXXXXXXX
我会得到像
这样的数据{"data":[{"duration_sec":2710,"sport":0,"speed_kmh_avg":11.721935764889876,"device_workout_id":"6588152507813057122","feed_id":155634169,"sport2":0,"id":192960126,"altitude_m_max":227.3,"hydration":0.35771,"altitude_m_min":145.5,"has_playlist":false,"burgers_burned":1.075926,"start_time":"2013-05-21 18:57:04 UTC","calories":581,"speed_kmh_max":26.281,"distance_km":8.824012756347656,"has_points":true},]}
但不知怎的,通过使用GWT http请求构建器调用它我不能这样做。我应该在代码中更改什么?
String url = "http://api.mobile.endomondo.com/mobile/api/workout/list?authToken=XXXXXXXXXX";
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request myrequest = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
trainingsJSON = JSONParser.parseStrict(response.getText());
trainingsString = response.getText();
Label l = new Label();
l.setText("200 erros status code JSON DATA from endomondo " + response.getText()) ;
RootPanel.get().add(l);
} else {
// Handle the error. Can get the status text from response.getStatusText()
Label l = new Label();
l.setText("JSON DATA from endomondo 3rror part " + response.getText()) ;
RootPanel.get().add(l);
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
修改
我尝试过添加
builder.setHeader("Access-Control-Allow-Origin", "*");
但没有运气。
答案 0 :(得分:1)
当您使用GWT发出CORS请求时,您不必为请求添加任何额外的标头。您必须做的是检查服务器是否支持来自您站点的CORS请求。
如果您管理网站http://api.mobile.endomondo.com
,则必须更改服务器代码,以便在客户端发送OPTION
请求时返回相应的CORS标头。
对于java服务器端,您有一个如何使用Filter
在此page中处理CORS的示例。
请注意,CORS仅适用于现代浏览器(EDITED:实际上某些浏览器的旧版本支持它。请参阅下面@Thomas评论中的浏览器列表)。