facebook twitter hatena line email

「Android/HttpRequest通信/HttpURLConnection」の版間の差分

提供: 初心者エンジニアの簡易メモ
移動: 案内検索
(ua参考コード)
(サンプル)
行5: 行5:
 
==サンプル==
 
==サンプル==
 
同期処理のみ(AsyncTaskなどで実行すること)
 
同期処理のみ(AsyncTaskなどで実行すること)
import java.io.BufferedReader;
+
CustomHttpURLConnection http = new CustomHttpURLConnection();
import java.io.IOException;
+
http.request("https://api.github.com/feeds");
import java.io.InputStream;
+
 
import java.io.InputStreamReader;
+
<pre>
import java.net.HttpURLConnection;
+
import java.io.BufferedReader;
import java.net.SocketTimeoutException;
+
import java.io.IOException;
import java.net.URL;
+
import java.io.InputStream;
  String strGetUrl = "https://api.github.com/feeds";
+
import java.io.InputStreamReader;
  // System.setProperty("http.agent", "Dalvik/2.1.0 (Linux; U; Android 9; H8216 Build/PDP-PKQ1.180708.001-10229)"); // System.getProperty("http.agent");
+
import java.net.HttpURLConnection;
  Log.i("HttpURLConnection", "ua=" + System.getProperty("http.agent"));
+
import java.net.SocketTimeoutException;
  HttpURLConnection urlConn = null;
+
import java.net.URL;
  InputStream in = null;
+
import android.util.Log;
  BufferedReader reader = null;
+
 
  try {
+
class CustomHttpURLConnection
      URL url = new URL(strGetUrl);
+
{
      urlConn = (HttpURLConnection) url.openConnection();
+
    public void request(String strGetUrl) {
      urlConn.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
+
        // System.setProperty("http.agent", "Dalvik/2.1.0 (Linux; U; Android 9; H8216 Build/PDP-PKQ1.180708.001-10229)"); // System.getProperty("http.agent");
      urlConn.setRequestMethod("GET");
+
        Log.i("HttpURLConnection", "ua=" + System.getProperty("http.agent"));
//      urlConn.setRequestMethod("POST");
+
        HttpURLConnection urlConn = null;
      urlConn.setConnectTimeout(10000); // 10s
+
        InputStream in = null;
      urlConn.setReadTimeout(1000); // 1s
+
        BufferedReader reader = null;
      urlConn.connect();
+
        try {
      int status = urlConn.getResponseCode();
+
            URL url = new URL(strGetUrl);
      Log.i("HttpURLConnection","status_code=" + status);
+
            urlConn = (HttpURLConnection) url.openConnection();
      if (status == HttpURLConnection.HTTP_OK) {
+
            urlConn.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
          in = urlConn.getInputStream();
+
            urlConn.setRequestMethod("GET");
          reader = new BufferedReader(new InputStreamReader(in));
+
//      urlConn.setRequestMethod("POST");
          StringBuilder output = new StringBuilder();
+
            urlConn.setConnectTimeout(10000); // 10s
          String line;
+
            urlConn.setReadTimeout(1000); // 1s
          while ((line = reader.readLine()) != null) {
+
            urlConn.connect();
              output.append(line);
+
            int status = urlConn.getResponseCode();
          }
+
            Log.i("HttpURLConnection", "status_code=" + status);
          Log.i("HttpURLConnection", "res=" + output.toString());
+
            if (status == HttpURLConnection.HTTP_OK) {
      }
+
                in = urlConn.getInputStream();
  } catch (SocketTimeoutException e) {
+
                reader = new BufferedReader(new InputStreamReader(in));
      e.printStackTrace();
+
                StringBuilder output = new StringBuilder();
  } catch (IOException e) {
+
                String line;
      e.printStackTrace();
+
                while ((line = reader.readLine()) != null) {
  } finally {
+
                    output.append(line);
      try {
+
                }
          if (reader != null) {
+
                Log.i("HttpURLConnection", "res=" + output.toString());
              reader.close();
+
            }
          }
+
        } catch (SocketTimeoutException e) {
          if (urlConn != null) {
+
            e.printStackTrace();
              urlConn.disconnect();
+
        } catch (IOException e) {
          }
+
            e.printStackTrace();
      } catch (IOException e) {
+
        } finally {
          e.printStackTrace();
+
            try {
      }
+
                if (reader != null) {
  }
+
                    reader.close();
 +
                }
 +
                if (urlConn != null) {
 +
                    urlConn.disconnect();
 +
                }
 +
            } catch (IOException e) {
 +
                e.printStackTrace();
 +
            }
 +
        }
 +
    }
 +
}
 +
</pre>
  
 
uaはサーバに接続して変更設定されていることを確認済み。
 
uaはサーバに接続して変更設定されていることを確認済み。

2018年12月14日 (金) 14:05時点における版

準備

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

サンプル

同期処理のみ(AsyncTaskなどで実行すること) CustomHttpURLConnection http = new CustomHttpURLConnection(); http.request("https://api.github.com/feeds");

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;
import android.util.Log;

class CustomHttpURLConnection
{
    public void request(String strGetUrl) {
        // 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

uaを設定しない場合とwebviewからもてっくる場合

HttpURLConnectionのuaデフォ(System.getProperty("http.agent");)

Dalvik/2.1.0 (Linux; U; Android 9; Pixel 2 XL Build/PPR2.181005.003)

webviewのua android/webview/useragent [ショートカット]

Mozilla/5.0 (Linux; Android 9; Pixel 2 XL Build/PPR2.181005.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/70.0.3538.110 Mobile Safari/537.36

retry処理

本来のget処理をexecGetCore()に入れる

    public boolean execGet() throws Exception {
        Exception tmpException = null;
        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;
    }