私はGitHubアカウントからリポジトリ情報を取得するためにAndroidアプリを作成しています。 GitHubアカウントhttps://github.com/vGrynishynからリポジトリデータを取得する機能。 Androidスタジオを使用して結果が2〜3回しか受信されなかった場合、urlConnection.getResponseCode()
:android.os.NetworkOnMainThreadException
に次の例外が表示されます。 しかし、私はIntelij IDEA(コマンドラインアプリ)で実行しようとしましたが、問題なくいつでも動作しています。AndroidスタジオGitHub APIリクエストからの返品
どこにエラーがありますか教えてください。
private String getGitHubRepositoryContent(){
String line = null;
try {
URL url = new URL("https://api.github.com/users/vGrynishyn/repos");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
InputStream in;
if (urlConnection.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST) {
in = urlConnection.getInputStream();
} else {
in = urlConnection.getErrorStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
while (br.read() != -1) {
line = br.readLine();
}
System.out.println("Response code: " + responseCode);
System.out.println(line);
} catch (Exception e) {
e.printStackTrace(); //do something
}
return line;
}
ありがとうございます!それはasynctaskにあったが、私はそれを単純な関数に移した。私はなぜO_oを知りません – VovaG
あなたは歓迎です、私の答えをマークすることを忘れないでください:) –