restapi调用在java上工作,但在android上不工作(filenotfound)

pcww981p  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(377)

在我的android应用程序中,我正在对数据库进行异步调用,以获取体育提要(以下是此链接中的api文档:https://www.mysportsfeeds.com/data-feeds/api-docs/ (导航到“季节性运动会”部分)。
下面是我的android代码(与我在eclipse中启动的java代码完全相同,它返回了正确的数据):

// Launch an API request to MySportsFeeds to retrieve the schedule for NBA matches
try {
    URL url = new URL("https://api.mysportsfeeds.com/v2.1/pull/nfl/current/games.json");
    String encoding = java.util.Base64.getEncoder().encodeToString("[I_PUT_THE_CORRECT_API_KEY_HERE]:MYSPORTSFEEDS".getBytes());

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    InputStream content = (InputStream)connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));

    String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception ex) {
        System.out.println("Exception: " + ex.toString());
    }
}

这给了我以下错误:
java.io.filenotfoundexception异常:https://api.mysportsfeeds.com/v2.1/pull/nfl/current/games.json
这看起来很奇怪,因为android和java代码是完全相同的,而且我已经在我的系统中启用了相关的权限 AndroidManifest.xml 文件:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
7eumitmz

7eumitmz1#

删除行: connection.setDoOutput(true); 为我解决了这个问题。

n3h0vuf2

n3h0vuf22#

我有类似的问题,我尝试了这个,它的工作!!

String basicAuth = "Basic " + Base64.encodeToString("user:password".getBytes(), Base64.NO_WRAP);

因为你在android上编码,试试看 Base64.NO_WRAP 在android的编码方法中。

相关问题