facebook twitter hatena line email

Android/HttpRequest通信/HttpURLConnection

提供: 初心者エンジニアの簡易メモ
2018年8月6日 (月) 16:28時点におけるAdmin (トーク | 投稿記録)による版 (サンプル)

移動: 案内検索

サンプル

同期処理のみ(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();
     }
 }

参考

https://itsakura.com/java-httpurlconnection

http://d.hatena.ne.jp/Kazuhira/20131026/1382796711