Android and Flutter HTTP Post Request with JSON Data
Android (Kotlin) Code
package com.example.modeldone.util
import android.os.Handler
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.IOException
object HttpUtil {
val okHttpClient = OkHttpClient()
val handler = Handler()
val baseUrl = "http://119.3.168.89:8080"
fun doPostForResult(url:String,jsonObject: JSONObject,listener: OnResultListener){
val data = jsonObject.toString()
val toMediaTypeOrNull = "application/json; charset=utf-8".toMediaTypeOrNull()
val toRequestBody = data.toRequestBody(toMediaTypeOrNull)
val build = Request.Builder()
.url(baseUrl + url)
.post(toRequestBody)
.build()
okHttpClient.newCall(build).enqueue(object : Callback{
override fun onFailure(call: Call, e: IOException) {
}
override fun onResponse(call: Call, response: Response) {
val string = response.body!!.string()
handler.post{ listener.OnResult(string) }
}
})
}
}
interface OnResultListener{
fun OnResult(data:String)
}
Flutter (Dart) Code
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class HttpUtil {
static final baseUrl = "http://119.3.168.89:8080";
static Future<void> doPostForResult(
String url, Map<String, dynamic> jsonObject, OnResultListener listener) async {
var data = json.encode(jsonObject);
var response = await http.post(
Uri.parse(baseUrl + url),
headers: {'Content-Type': 'application/json'},
body: data,
);
if (response.statusCode == 200) {
listener.onResult(response.body.toString());
} else {
throw Exception('Failed to post data');
}
}
}
abstract class OnResultListener {
void onResult(String data);
}
Explanation:
- Android: This code uses the OkHttp library to make a POST request with JSON data. It utilizes a
Handlerto update the UI thread after receiving the response. - Flutter: This code uses the
httppackage to make the same POST request. It usesasync/awaitto handle the asynchronous operation and checks the response status code before calling theOnResultListener.
Key Points:
- Both codes include a base URL for the API endpoint.
- They both serialize the JSON data using
JSONObject.toString()(Android) andjson.encode()(Flutter) respectively. - They both set the
Content-Typeheader toapplication/jsonin the request. - Both codes use an interface (
OnResultListener) to handle the response data, allowing for a consistent structure for handling network results.
This example provides a foundation for making POST requests with JSON data in both Android and Flutter. You can easily adapt it to your specific API requirements by modifying the URL, request parameters, and response handling logic.
原文地址: https://www.cveoy.top/t/topic/oXhF 著作权归作者所有。请勿转载和采集!