Cvan
Cvan

Reputation: 21

How to make a HTTP/POST request in Kotlin (Android) to simple server?

Hello I am trying to begin an Android app in Kotlin. I have been trying to find a way to simply send and receive data from an android app to a simple HTTP server I made on my computer. The idea I am hoping is just make an app with a text box on it and a send button. When I press the send button it sends it to the simple http server (whether I use IP address or URL isn't Important)

This is just simply a proof of concept that I can make my own simple HTTP Server and get the app to send and receive from it.

I am essentially trying to do a server-client architecture between an android app and a computer. I can get this concept to work between two computer applications (python, java, C++ etc) but not how to do it in android. I keep looking for other answers on here but still come up short.

to be specific do I need enable certain features within the configurations file or a library that will allow the task to be done in the background?

Thank you for your help in advance.

Upvotes: 2

Views: 9480

Answers (3)

Sagar
Sagar

Reputation: 21

Post Api request Using okHttp in Kotlin (Android)

follow steps

  1. You will need to add the dependencies in build.gradle(:app)

    implementation("com.squareup.okhttp3:okhttp:4.9.0")

  2. request code here

     fun runPostApi() {
     var url = "https://reqres.in/api/users"
    
     // add parameter
     val formBody = FormBody.Builder().add("name", " Parker")
             .build()
    
     // creating request
     var request = Request.Builder().url(url)
             .post(formBody)
             .build()
    
     var client = OkHttpClient();
     client.newCall(request).enqueue(object : Callback {
         override fun onResponse(call: Call, response: Response) {
             println(response.body?.string())
    
         }
    
         override fun onFailure(call: Call, e: IOException) {
             println(e.message.toString())
         }
     })}
    

for more information link here below https://square.github.io/okhttp/recipes/

Upvotes: 1

Er.Prem Singh daksha
Er.Prem Singh daksha

Reputation: 403

If you want to connect of server for sending requests (POST and GET) then follow this code

    public void callApi(String urls,String calledFor) {
        
    
    try {
            HttpGet httppost = new HttpGet(urls);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);
    
            int status = response.getStatusLine().getStatusCode();
    
            if (status == 200) {
                HttpEntity entity = response.getEntity();
                String data = EntityUtils.toString(entity);
                JSONObject jsono = new JSONObject(data);
                JSONObject json = jsono.getJSONObject("data");
    
            }
    
        } catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
 }

Upvotes: 2

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 3001

ktor is a wonderful HTTP client that you can use for Android. It is developed by JetBrains, who are also authors of Kotlin, so it takes advantage of the features of the language:

You will need to add the ktor client for Android in build.gradle:

implementation "io.ktor:ktor-client-android:$ktor_version"

Then set up your client like this:

val client = HttpClient(Android) {
    // setting these properties is optional; you don't need to if you wish to use the defaults
    engine {
        connectTimeout = 100_000
        socketTimeout = 100_000
    }
}

At last you can make HTTP requests like so (example from here): (the use method is to automatically close it at the end, make sure you read about releasing resources)

val resp: String = client.use {
    val htmlContent = it.get<String>("https://en.wikipedia.org/wiki/Main_Page")
    println(htmlContent)
    // same as
    val content: String = it.get("https://en.wikipedia.org/wiki/Main_Page")
    content
}

Upvotes: 1

Related Questions