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