Androidクライアントからサーバーへのデータ操作実装

Android端末からアプリケーションサーバーに対してデータ削除・追加・更新を行う実装方法について解説します。本実装ではHTTP通信を介したRESTfulインターフェースを前提とし、非同期処理によるリクエスト送信を実現します。

データ削除処理の実装

削除操作は特定IDを含むDELETEリクエストで実行します。UI要素の削除ボタンクリック時にIDを取得し、通信スレッドを起動します。

deleteButton.setOnClickListener(v -> {
    String targetId = idTextView.getText().toString();
    new ApiRequestTask(RequestType.DELETE, targetId).execute();
});

共通リクエスト処理クラスではメソッドタイプに応じてエンドポイントを切り替えます。

private enum RequestType { DELETE, CREATE, UPDATE }

private String buildEndpoint(RequestType type, String id) {
    switch(type) {
        case DELETE: return BASE_URL + "/records/" + id;
        case CREATE: return BASE_URL + "/records";
        default: return BASE_URL + "/records/" + id;
    }
}

データ追加処理の実装

新規データ登録にはPOSTメソッドを使用し、フォームデータをURLエンコードして送信します。以下は非同期タスク内の実装例です。

private void executeCreate(String name, String description) {
    HttpURLConnection connection = null;
    try {
        URL url = new URL(buildEndpoint(RequestType.CREATE, null));
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);

        String params = "name=" + URLEncoder.encode(name, "UTF-8") +
                        "&comment=" + URLEncoder.encode(description, "UTF-8");
        
        try (OutputStream os = connection.getOutputStream()) {
            os.write(params.getBytes(StandardCharsets.UTF_8));
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            publishResult(RESULT_SUCCESS);
        } else {
            handleErrorResponse(connection);
        }
    } catch (IOException e) {
        publishError(e.getMessage());
    } finally {
        if (connection != null) connection.disconnect();
    }
}

データ更新処理の実装

更新操作はPUTメソッドで実装し、既存リソースの修正を行います。パラメータ構築部分は追加処理と類似しますが、エンドポイントにリソースIDを含めます。

private void executeUpdate(String id, String name, String description) {
    String endpoint = buildEndpoint(RequestType.UPDATE, id);
    // POST処理と同様の実装ですが、RequestMethodをPUTに変更
    // パラメータにidを含める点が削除/追加と異なる
}

通信処理の最適化

共通化された通信ロジックでは以下のポイントに留意します。

  • 文字エンコーディングを明示的にUTF-8で指定
  • レスポンスコード200系以外はエラーハンドリング
  • 接続タイムアウトを30秒に設定
  • バックグラウンドスレッドでネットワーク操作を実行
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);

タグ: Android HTTP通信 非同期処理 restful URLConnection

5月22日 10:30 投稿