首页 > 解决方案 > Android OkHTTP返回不一致的字符串?

问题描述

我正在使用 OkHTTP 来简单地从 url 的正文中获取文本:

class DownloadUrl {
    String readUrl(String myUrl) throws IOException,NullPointerException {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url(myUrl)
            .build();

        Response response = client.newCall(request).execute();

        return response.body().string();
    }
}

但是,尽管 URL 及其内容每次都相同,但我得到的字符串不一致。例如,一些返回的字符串遗漏了 JSON 块,我应该得到这个:

"html_attributions" : [],
   "results" : [
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/shopping-71.png",
         "id" : "b89943f74e20eafb8959ace996a6f35cd303d5ff",
         "name" : "Circle K",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 400,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/114668422179892290420/photos\"\u003eCircle K\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAAdubSCt5u9IrI6bsL91DGLdIm2SMO39SaKGxKKmrj-ygxrCmIjUzG0DwrBgcX56DdpEFRBev29cdA4ljZnIR7lvPlP3jBhHkBxliRkGlAlfkAh9TiQvVuyNNQLnzIcsuEhAsc0Px0hV4mFTZruHRWLh9GhTIePuzk5JxV1QewH3jimkAKIzALw",
               "width" : 400
            }
         ],  

相反,我得到:

"html_attributions" : [],
   "results" : [
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
         "id" : "1a830f99aab4e7afa143b2c8d03545ea7c1e9432",
         "name" : "McDonald's",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },

JSON的“照片”部分被留在了一些电话中,有什么想法吗?谢谢。

标签: androidokhttp

解决方案


根据Google Place Search 文档(我猜这是您正在使用的服务),每个result对象可能包含:

photos[]— 对象数组photo,每个对象都包含对图像的引用。地点搜索最多会返回一个photo对象

此外,Google Place Photos 文档报告说:

如果该地点有相关的照片内容,则响应 [...] 将包含一个photos[]字段。

这意味着如果特定结果没有照片,则photos响应中根本不会出现数组。

您提供的示例不是指同一个地方:在第一种情况下,您将获得“Circle K”的结果,而在第二种情况下,您将获得“McDonald's”的结果。基于此,响应似乎与文档所说的一致。


推荐阅读