java.io.FileNotFoundException, генерируемый для определенных URL-адресов в списке (API BingSearch) - PullRequest
1 голос
/ 31 марта 2019

Я уже некоторое время пытаюсь заставить API поиска Bing работать в моем проекте Android, и я в основном добился успеха. Однако некоторые запросы, которые я передаю API, дают мне java.io.FileNotFoundException. Я не могу понять почему, так как я протестировал эти значения запросов в Postman, и данные поступают, как и ожидалось. Вот мой класс BingSearch, а также соответствующий фрагмент кода:

Вызовите API BingSearch

public void getUrls() {
    try {
        ....
            try {
                //song format: "Song, Artist"
                idRuntimes.add(new BingSearch.GetSearch().execute(songs.get(i)).get());
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        ...

}

Класс BingSearch

public class BingSearch {

    static String subscriptionKey = "subscription_key";

    // Verify the endpoint URI.  At this writing, only one endpoint is used for Bing
    // search APIs.  In the future, regional endpoints may be available.  If you
    // encounter unexpected authorization errors, double-check this value against
    // the endpoint for your Bing Web search instance in your Azure dashboard.
    static String host = "https://api.cognitive.microsoft.com";
    static String path = "/bing/v7.0/videos/search";

    static String searchTerm;

    static String videoId, runtime;
    private static String TAG = "BingSearch";

    public BingSearch(String term) {
        searchTerm = term.replaceAll("[^A-Za-z0-9%\\[\\]]", "");

        try {
            String complete = new GetSearch().execute().get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static SearchResults SearchVideos (String searchQuery) throws Exception {
        // construct URL of search request (endpoint + query string)
        URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchQuery, "UTF-8"));
        HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
        connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);

        // receive JSON body
        InputStream stream = connection.getInputStream();
        String response = new Scanner(stream).useDelimiter("\\A").next();

        // construct result object for return
        SearchResults results = new SearchResults(new HashMap<>(), response);

        // extract Bing-related HTTP headers
        Map<String, List<String>> headers = connection.getHeaderFields();
        for (String header : headers.keySet()) {
            if (header == null) continue;      // may have null key
            if (header.startsWith("BingAPIs-") || header.startsWith("X-MSEdge-")) {
                results.relevantHeaders.put(header, headers.get(header).get(0));
            }
        }

        stream.close();
        return results;
    }

    // pretty-printer for JSON; uses GSON parser to parse and re-serialize
    public static String prettify(String json_text) {
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(json_text).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(json);
    }

    public static class GetSearch extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params) {
            try {
                SearchResults result = SearchVideos(params[0]);

                //Log.d("BING", "\nRelevant HTTP Headers:\n");
                for (String header : result.relevantHeaders.keySet())
                    Log.d("BING", header + ": " + result.relevantHeaders.get(header));

                //Log.d("BING", "\nJSON Response:\n");
                Log.d("BING", prettify(result.jsonResponse));

                Gson gson = new Gson();
                String jsonOutput = result.jsonResponse;
                Type listType = new TypeToken<VideoResults>(){}.getType();
                VideoResults results = gson.fromJson(jsonOutput, listType);
                videoId = results.getValue().get(0).getContentUrl();
                runtime = results.getValue().get(0).getDuration();

                Log.d("SearchResult: " + params[0], videoId + " | " + runtime);
            }
            catch (Exception e) {
                Log.d("Error-" + TAG, e.toString());
            }
            return videoId + "," + runtime;
        }
    }
}

// Container class for search results encapsulates relevant headers and JSON data
class SearchResults{
    HashMap<String, String> relevantHeaders;
    String jsonResponse;
    SearchResults(HashMap<String, String> headers, String json) {
        relevantHeaders = headers;
        jsonResponse = json;
    }
}

ОШИБКИ (только 2 из списка из 7 запросов)

D/Error-BingSearch: java.io.FileNotFoundException: https://api.cognitive.microsoft.com/bing/v7.0/videos/search?q=House+In+LA%2C+Jungle
D/Error-BingSearch: java.io.FileNotFoundException: https://api.cognitive.microsoft.com/bing/v7.0/videos/search?q=Cherry%2C+Jungle
...