|
1: 2016-08-23 (火) 05:20:42 njf |
| + | Androidの標準APIで用意されていたHttpClientはFroyo以降では使えなくなるので、HttpURLConnectionに移行しました。 |
| | | |
| + | 実際の開発にはOkHttpなどが人気のようですが、設定ファイルを取得するなどの簡単な物ならHttpURLConnectionで十分です。 |
| + | |
| + | GETでページの情報だけを取ってくるなら、 |
| + | try { |
| + | URL url = new URL(YOUR_URL); |
| + | HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); |
| + | try { |
| + | InputStream in = new BufferedInputStream(urlConnection.getInputStream()); |
| + | byte bodyByte[] = new byte[1024]; |
| + | int readLen = in.read(bodyByte); |
| + | in.close(); |
| + | return new String(bodyByte,0,readLen, "UTF-8"); |
| + | }catch (Exception e){ |
| + | urlConnection.disconnect(); |
| + | Log.d(LOG_TAG,"connection error"); |
| + | return null; |
| + | } |
| + | } |
| + | |
| + | このようになります。ここでbyte[1024]はページのサイズに合わせてそれより大きな値に変更してください。 |
| + | また、UIスレッドからネットワークにアクセスするとエラーになるのは以前と同じなので、その場合はAsyncTaskなどを使う必要があります。 |
Counter: 2150,
today: 3,
yesterday: 1