「Android/HttpRequest通信/HttpURLConnection」の版間の差分
提供: 初心者エンジニアの簡易メモ
行63: | 行63: | ||
http://d.hatena.ne.jp/Kazuhira/20131026/1382796711 | http://d.hatena.ne.jp/Kazuhira/20131026/1382796711 | ||
+ | |||
+ | ==retry処理== | ||
+ | 本来のget処理をexecGetCore()に入れる | ||
+ | <pre> | ||
+ | public boolean execGet() throws Exception { | ||
+ | Exception tmpException = new Exception("other"); | ||
+ | for (int retry = 0; retry <= mRetry; retry++) { | ||
+ | try { | ||
+ | boolean ret = execGetCore(); | ||
+ | if (ret) { | ||
+ | return ret; | ||
+ | } | ||
+ | } catch (Exception e) { | ||
+ | tmpException = e; | ||
+ | } | ||
+ | } | ||
+ | if (Exception != null) { | ||
+ | throw tmpException; | ||
+ | } | ||
+ | return false; | ||
+ | } | ||
+ | </pre> |
2018年12月3日 (月) 18:05時点における版
サンプル
同期処理のみ(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.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); 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(); } }
uaはサーバに接続して変更設定されていることを確認済み。
ドメイン接続許可しないエラーが出るときはこちらを確認
android/開発環境/Android8 [ショートカット]
参考
https://itsakura.com/java-httpurlconnection
http://d.hatena.ne.jp/Kazuhira/20131026/1382796711
retry処理
本来のget処理をexecGetCore()に入れる
public boolean execGet() throws Exception { Exception tmpException = new Exception("other"); for (int retry = 0; retry <= mRetry; retry++) { try { boolean ret = execGetCore(); if (ret) { return ret; } } catch (Exception e) { tmpException = e; } } if (Exception != null) { throw tmpException; } return false; }