androidのHTTP通信のユーティリティを作った。

HTTP通信で取得したいものはいろいろある。

これらをユーティル化した。


■HTTP通信の処理
バイト配列で取得すればあとでhtmlでも、xmlでもjsonでも好きなように扱える。
HTML、XMLJSONならバイト配列→文字列変換で対応できる。
画像ならバイト配列→Bitmapに変換
いずれもHTTP通信でバイト変換する処理を共通化できる。

	public static byte[] getByteArrayFromURL(String strUrl) {
		byte[] line = new byte[1024];
		byte[] result = null;
		HttpURLConnection con = null;
		InputStream in = null;
		ByteArrayOutputStream out = null;
		int size = 0;
		try {
			// HTTP接続のオープン
			URL url = new URL(strUrl);
			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");
			con.connect();
			in = con.getInputStream();

			// バイト配列の読み込み
			out = new ByteArrayOutputStream();
			while (true) {
				size = in.read(line);
				if (size <= 0) {
					break;
				}
				out.write(line, 0, size);
			}
			result = out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (con != null)
					con.disconnect();
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

■HTMLの取得
バイト配列→文字列変換

	public static String getHtml(String url) {
		byte[] byteArray = Util.getByteArrayFromURL(url);
		String html = new String(byteArray);
		return html;
	}

■画像
バイト配列→Bitmap変換

	public static Bitmap getImage(String url) {
		byte[] byteArray = getByteArrayFromURL(url);
		return BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
	}

XML
別記事で説明

JSON
まだ未実装