首页 > 解决方案 > Foursquare API 请求在使用浏览器与 jsonparsing 时错过了一些价值

问题描述

我正在尝试从 Foursquare 的 API 请求(HTTP 请求)中获取 JSON 信息。当我将 HTTP 链接粘贴到浏览器上时,我能够获取所有 JSON 信息。但是,当我尝试对我的 Android Studio 上的链接进行 JSON 解析时,我错过了 JSON 对象中的一些值。我包含了来自 Web 浏览器的 JSON 结果,如下所示。如果您看到“items”的 JSONarray 应该具有“reasons”、“snippet”、“venue”、“photo”、“tips”、“referralId”的 JSONobject。但是当我解析它们时,我只能得到“原因”、“地点”和“referralId”。

我尝试使用以下两种方法解析链接:

  1. 在单独的类中获取 JSON 数据
  2. 使用 OkHttpClient
  3. 排球库

与我直接在浏览器上复制/粘贴 URL 链接相比,所有方法都给了我类似的 JSON 结果,这是缺少值(只有“原因”、“地点”和“referralId”)的结果。

这是我尝试使用方法 1(获取数据)的代码。在这种情况下,数据应该在运行 fetchJson().start() 时包含 JSON 信息

private class fetchJson extends Thread{
        @Override
        public void run() {
            String url = link; //link contains the HTTPS address
            String data = "";

            try {
                URL url = new URL(link);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line;

                while ((line = bufferedReader.readLine()) != null){
                    data = data + line;
                }

                Log.d("fetchJson", "the url has been turned into the following json: " + data);

            } catch (MalformedURLException e) {
                Log.e("fetchJson", "run: problem with getting the URL is: " + e );
            } catch (IOException e) {
                Log.e("fetchJson", "run: problem with HttpURLConnection is: " + e );
            }
        }
    }

方法2,使用OkHttpClient:

private void JsonParse() {
        
        String url = link;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(link).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    String myResponse = response.body().string();
                    FoodActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "run: the url link should turn into json of: " + myResponse);
                        }
                    });
                }
            }
        });
  }

与我只是将链接直接粘贴到网络浏览器(即谷歌浏览器)相比,我尝试的所有方法都错过了一些价值。

有人可以帮我为什么会这样吗?URL 链接是否受到提供 API 的公司的某种程度的保护?

让我真正好奇的是,浏览器的 JSON 结果比我在 Android Studio 上解析它提供的信息更多。

非常感谢您的时间和帮助。

如果我只是将来自 Foursquare 的 API 请求 HTTP 直接粘贴到 Web 浏览器,这是 JSON 结果:

{
        "type": "Recommended Places",
        "name": "recommended",
        "items": [
          {
            "reasons": {
              "count": 0,
              "items": [
                {
                  "summary": "This spot is popular",
                  "pluralSummary": "These spots are popular",
                  "type": "general",
                  "reasonName": "globalInteractionReason"
                }
              ]
            },
            "snippets": {
              "count": 1,
              "items": [
                {
                  "detail": {
                    "type": "tip",
                    "object": {
                      "id": "510e4f83e4b0a910cfb115fa",
                      "createdAt": 1359892355,
                      "text": "Excellent and fast serviceeee!",
                      "type": "user",
                      "canonicalUrl": "https://foursquare.com/item/510e4f83e4b0a910cfb115fa",
                      "canonicalPath": "/item/510e4f83e4b0a910cfb115fa",
                      "likes": {
                        "count": 3,
                        "groups": [],
                        "summary": "3 likes"
                      },
                      "logView": true,
                      "agreeCount": 3,
                      "disagreeCount": 0,
                      "todo": {
                        "count": 0
                      },
                      "user": {
                        "id": "2222367",
                        "firstName": "Shella",
                        "lastName": "Kurnia",
                        "gender": "female",
                        "countryCode": "ID",
                        "canonicalUrl": "https://foursquare.com/user/2222367",
                        "canonicalPath": "/shellakurnia",
                        "photo": {
                          "prefix": "https://fastly.4sqi.net/img/user/",
                          "suffix": "/2222367-PBSNYEIYGTBOQUFA.jpg"
                        },
                        "isAnonymous": false
                      }
                    }
                  }
                }
              ]
            },
            "venue": {
              "id": "5104fbbbe4b0e45fff4b283b",
              "name": "Sushi Tei",
              "contact": {
                "phone": "02123581808",
                "formattedPhone": "(021) 23581808",
                "twitter": "sushi_tei_indo"
              },
              "location": {
                "address": "Grand Indonesia Shopping Town, West Mall Level LG #01",
                "crossStreet": "Jalan Mohammad Husni Thamrin No. 1",
                "lat": -6.194921701627258,
                "lng": 106.82020811973646,
                "labeledLatLngs": [
                  {
                    "label": "display",
                    "lat": -6.194921701627258,
                    "lng": 106.82020811973646
                  }
                ],
                "distance": 1429,
                "postalCode": "10310",
                "cc": "ID",
                "neighborhood": "Tanah Abang",
                "city": "Jakarta Pusat",
                "state": "DKI Jakarta",
                "country": "Indonesia",
                "contextLine": "Tanah Abang",
                "contextGeoId": 10003354,
                "formattedAddress": [
                  "<span itemprop=\"streetAddress\">Grand Indonesia Shopping Town, West Mall Level LG #01</span> (Jalan Mohammad Husni Thamrin No. 1)",
                  "<span itemprop=\"addressLocality\">Jakarta Pusat</span>",
                  "<span itemprop=\"addressRegion\">DKI Jakarta</span> <span itemprop=\"postalCode\">10310</span>"
                ]
              },
              "canonicalUrl": "https://foursquare.com/v/sushi-tei/5104fbbbe4b0e45fff4b283b",
              "canonicalPath": "/v/sushi-tei/5104fbbbe4b0e45fff4b283b",
              "categories": [
                {
                  "id": "4bf58dd8d48988d1d2941735",
                  "name": "Sushi Restaurant",
                  "pluralName": "Sushi Restaurants",
                  "shortName": "Sushi",
                  "icon": {
                    "prefix": "https://ss3.4sqi.net/img/categories_v2/food/sushi_",
                    "mapPrefix": "https://ss3.4sqi.net/img/categories_map/food/sushi",
                    "suffix": ".png"
                  },
                  "primary": true
                }
              ],
              "verified": false,
              "stats": {
                "tipCount": 52,
                "usersCount": 6808,
                "checkinsCount": 11537
              },
              "url": "http://www.sushitei.co.id",
              "urlSig": "+Zg8kvyty2HzOo2a8hC68JgZC4Q=",
              "price": {
                "tier": 2,
                "message": "Moderate",
                "currency": "$"
              },
              "rating": 8.2,
              "ratingColor": "73CF42",
              "ratingSignals": 343,
              "allowMenuUrlEdit": true,
              "beenHere": {
                "count": 0,
                "marked": false,
                "lastCheckinExpiredAt": 0
              },
              "hours": {
                "status": "Likely open",
                "richStatus": {
                  "entities": [],
                  "text": "Likely open"
                },
                "isOpen": true,
                "isLocalHoliday": false
              },
              "photos": {
                "count": 0,
                "groups": []
              },
              "hereNow": {
                "count": 0,
                "summary": "Nobody here",
                "groups": []
              },
              "popularityByGeo": 0.9993038843050234
            },
            "photo": {
              "id": "5193b67b498e3ea624b42a3a",
              "createdAt": 1368635003,
              "prefix": "https://fastly.4sqi.net/img/general/",
              "suffix": "/2192153_WZQfUpxj8aWxqfaUqSAjOKIY6QpNOcoGos8jqrkceoM.jpg",
              "width": 1920,
              "height": 1440,
              "visibility": "public"
            },
            "tips": [
              {
                "id": "510e4f83e4b0a910cfb115fa",
                "createdAt": 1359892355,
                "text": "Excellent and fast serviceeee!",
                "type": "user",
                "canonicalUrl": "https://foursquare.com/item/510e4f83e4b0a910cfb115fa",
                "canonicalPath": "/item/510e4f83e4b0a910cfb115fa",
                "likes": {
                  "count": 3,
                  "groups": [],
                  "summary": "3 likes"
                },
                "logView": true,
                "agreeCount": 3,
                "disagreeCount": 0,
                "todo": {
                  "count": 0
                },
                "user": {
                  "id": "2222367",
                  "firstName": "Shella",
                  "lastName": "Kurnia",
                  "gender": "female",
                  "countryCode": "ID",
                  "canonicalUrl": "https://foursquare.com/user/2222367",
                  "canonicalPath": "/shellakurnia",
                  "photo": {
                    "prefix": "https://fastly.4sqi.net/img/user/",
                    "suffix": "/2222367-PBSNYEIYGTBOQUFA.jpg"
                  },
                  "isAnonymous": false
                }
              }
            ],
            "referralId": "e-0-5104fbbbe4b0e45fff4b283b-0"
          }
        ]
      }

标签: androidjsonapiandroid-studiofoursquare

解决方案


推荐阅读