戻る
■アプリからHTTPリクエストする例
上記の例ではデバイストークンをPHPに渡すために手動での作業が必要となる 実際のアプリでは、アプリ内からアプリからHTTPリクエストでPHPに渡すことになる 以下、アプリからHTTPリクエストする例 ■PHP test.php
<?php header('Content-Type: application/json; charset=utf-8'); echo json_encode(array( 'status' => 'OK', 'datetime' => date('Y/m/d H:i:s'), )); exit;
■Android(Kotlin) Kotlin: HTTP GET/POST サンプルコード(AsyncTask) | UBUNIFU INCORPORATED https://jp.ubunifu.co/development/kotlin-http-get-post-sample-code [Android] 非同期処理 AsyncTaskの使い方 https://akira-watson.com/android/asynctask.html [android開発] AndroidManifest.xmlの設定一覧(ネットワーク系) - 行け!偏差値40プログラマー http://hensa40.cutegirl.jp/archives/6501 まずは汎用HTTPリクエストクラスを作成する MainActivity.kt と同じ階層に HttpTask.kt を作成して以下を記述 パッケージ名はプロジェクトに合わせて調整する
package net.refirio.pushtest1 import android.os.AsyncTask import android.util.Log import java.io.* import java.net.HttpURLConnection import java.net.URL class HttpTask(callback: (String?) -> Unit) : AsyncTask<String, Unit, String>() { var callback = callback override fun doInBackground(vararg params: String): String? { val url = URL(params[1]) val httpClient = url.openConnection() as HttpURLConnection httpClient.setReadTimeout(10 * 1000) httpClient.setConnectTimeout(10 * 1000) httpClient.requestMethod = params[0] if (params[0] == "POST") { httpClient.instanceFollowRedirects = false httpClient.doOutput = true httpClient.doInput = true httpClient.useCaches = false httpClient.setRequestProperty("Content-Type", "application/json; charset=utf-8") } try { if (params[0] == "POST") { httpClient.connect() val os = httpClient.getOutputStream() val writer = BufferedWriter(OutputStreamWriter(os, "UTF-8")) writer.write(params[2]) writer.flush() writer.close() os.close() } if (httpClient.responseCode == HttpURLConnection.HTTP_OK) { val stream = BufferedInputStream(httpClient.inputStream) val data: String = readStream(inputStream = stream) return data } else { Log.d("HttpTask", "ERROR: ${httpClient.responseCode}") } } catch (e: Exception) { e.printStackTrace() } finally { httpClient.disconnect() } return null } fun readStream(inputStream: BufferedInputStream): String { val bufferedReader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() bufferedReader.forEachLine { stringBuilder.append(it) } return stringBuilder.toString() } override fun onPostExecute(result: String?) { super.onPostExecute(result) callback(result) } }
MainActivity.kt の onCreate 内に以下を記述
// HTTPリクエストのテスト HttpTask({ if (it == null) { Log.d("MainActivity", "Data is empty.") return@HttpTask } Log.d("MainActivity", "OK: ${it}") val json = JSONObject(it) val status = json.getString("status") val datetime = json.getString("datetime") Log.d("MainActivity", "status: ${status}") Log.d("MainActivity", "datetime: ${datetime}") }).execute("GET", "https://example.com/test.php")
インターネットにアクセスするため、AndroidManifest.xml に以下を追加 「<manifest>」の直下に追加すればいい
<uses-permission android:name="android.permission.INTERNET" />
■iOS(Kotlin) ViewController.swift の viewDidLoad 内に以下を記述
// HTTPリクエストのテスト if let url = URL(string: "https://example.com/test.php") { let request = URLRequest(url: url) let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in guard let data = data else { print("Data is empty.") return } do { let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) if let status = (json as AnyObject).object(forKey: "status") { print(status) } if let datetime = (json as AnyObject).object(forKey: "datetime") { print(datetime) } } catch { print("JSON parse error.") } print("Complete.") }) task.resume() }