「Android/HttpRequest通信/HttpURLConnection」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→サンプル) |
(→サンプル) |
||
行10: | 行10: | ||
urlConn = (HttpURLConnection) url.openConnection(); | urlConn = (HttpURLConnection) url.openConnection(); | ||
urlConn.setRequestMethod("GET"); | urlConn.setRequestMethod("GET"); | ||
− | // | + | // urlConn.setRequestMethod("POST"); |
urlConn.connect(); | urlConn.connect(); | ||
int status = urlConn.getResponseCode(); | int status = urlConn.getResponseCode(); |
2018年8月6日 (月) 16:28時点における版
サンプル
同期処理のみ(AsyncTaskなどで実行すること)
String strGetUrl = "https://api.github.com/feeds"; 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.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 (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } if (urlConn != null) { urlConn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } }