【问题标题】:GWT's http request builder returning empty responseGWT 的 http 请求构建器返回空响应
【发布时间】:2013-06-12 21:39:54
【问题描述】:

我有一个 GWT 应用程序,我想用它从 endomondo 获取 JSON 格式的数据,我可以通过以下 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", "*");

但没有运气。

【问题讨论】:

    标签: java gwt httprequest http-get


    【解决方案1】:

    当您使用 GWT 发出 CORS 请求时,您不必在请求中添加任何额外的标头。您必须做的是检查服务器是否支持来自您站点的 CORS 请求。

    如果您正在管理站点 http://api.mobile.endomondo.com,则必须更改服务器代码以在客户端发送 OPTION 请求时返回适当的 CORS 标头。

    在 java 服务器端的情况下,您有一个示例,说明如何使用 Filter 在此 page 中处理 CORS。

    请注意,CORS 仅适用于现代浏览器(已编辑:实际上某些浏览器的旧版本支持它。请参阅下面@Thomas cmets 中的浏览器列表)。

    【讨论】:

    • 注意:“现代浏览器”是指所有浏览器(Firefox、Chrome、Safari 多年,Opera 最近出现),但 IE9-(IE10 很好)。
    • 是的,IE9 不在“我的”现代浏览器列表中。感谢托马斯
    • 我还想指出,这里的“现代”包括多年前的浏览器(Firefox 3.5、Safari 4.0、Chrome——所有版本?至少从 4.0 开始——Android 2.1)caniuse.com/cors跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多