This example works only in Android Studio emulator and with accepting all certificates, and it is made with
Retrofit library.
First example of Web Api in .NET Core:
using Microsoft.AspNetCore.Mvc;
namespace WebApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public string Get()
{
return "test";
}
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
[HttpPost]
public string Post([FromBody] string value)
{
return $"Sent: {value}";
}
}
Now example in Kotlin.
In \app\src\main\AndroidManifest.xml I have added internet permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
In \app\src\main\res\layout\activity_main.xml I have added the button:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:onClick="postHttp"
tools:layout_editor_absoluteX="166dp"
tools:layout_editor_absoluteY="441dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
/>
</androidx.constraintlayout.widget.ConstraintLayout>
In \app\build.gradle I have added
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.okhttp3:okhttp:4.9.0"
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
Code to trust all certificates taken from
here.
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
Log.i(MainActivity::class.simpleName, "checkClientTrusted")
}
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
Log.i(MainActivity::class.simpleName, "checkServerTrusted")
}
override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
})
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
// connect to server
val client = OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager).hostnameVerifier{ _, _ -> true }.build()
Next building Retrofit:
val retro = Retrofit.Builder()
.baseUrl("https://10.0.2.2:7037")
.client(client)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
Here notice baseUrl: https://10.0.2.2:7037 - 10.0.2.2 is localhost for Android Studio emulator
Add WebApiService interface:
interface WebApiService {
@Headers("Content-Type: text/json")
@POST("/api/Values")
fun postMethod(@Body value: String): Call<String>
}
Create request:
val service = retro.create(WebApiService::class.java)
val webApiRequest = service.postMethod("\"test\"")
Here notice "\"test\"" since I am trying to send a raw string, otherwise would be rejected.
Last but not least, onResponse and onFailure:
val alertDialogBuilder = AlertDialog.Builder(this@MainActivity)
webApiRequest.enqueue(object : Callback<String> {
override fun onResponse(call: Call<String>, response: Response<String>) {
if (!response.isSuccessful) {
alertDialogBuilder.setMessage(response.errorBody()!!.charStream().readText())
.setCancelable(false)
.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, _ ->
dialog.dismiss()
})
val alert = alertDialogBuilder.create()
alert.setTitle("Error")
alert.show()
}
else {
alertDialogBuilder.setMessage("Response: ${response.body().toString()}")
.setCancelable(false)
.setNeutralButton("OK", DialogInterface.OnClickListener { dialog, _ ->
dialog.dismiss()
})
val alert = alertDialogBuilder.create()
alert.setTitle("Error")
alert.show()
}
}
override fun onFailure(call: Call<String>, t: Throwable) {
alertDialogBuilder.setMessage(t.message)
.setCancelable(false)
.setNeutralButton("OK", DialogInterface.OnClickListener {
dialog, _ -> dialog.dismiss()
})
val alert = alertDialogBuilder.create()
alert.setTitle("Error")
alert.show()
}
})
.NET solution download from
here and Android source code download from here
here.