Android/HttpRequest通信/HttpURLConnection
提供: 初心者エンジニアの簡易メモ
サンプル
同期処理のみ(AsyncTaskなどで実行すること)
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; String strGetUrl = "https://api.github.com/feeds"; // System.setProperty("http.agent", "Dalvik/2.1.0 (Linux; U; Android 9; H8216 Build/PDP-PKQ1.180708.001-10229)"); // System.getProperty("http.agent"); Log.i("HttpURLConnection", "ua=" + System.getProperty("http.agent")); HttpURLConnection urlConn = null; InputStream in = null; BufferedReader reader = null; try { URL url = new URL(strGetUrl); urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestMethod("GET"); // urlConn.setRequestMethod("POST"); urlConn.setConnectTimeout(10000); // 10s urlConn.setReadTimeout(1000); // 1s urlConn.connect(); int status = urlConn.getResponseCode(); Log.i("HttpURLConnection","status_code=" + status); if (status == HttpURLConnection.HTTP_OK) { in = urlConn.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder output = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { output.append(line); } Log.i("HttpURLConnection", "res=" + output.toString()); } } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } }
ドメインエラーが出るときはこちらを確認
android/開発環境/Android8 [ショートカット]