简体   繁体   中英

How can I make a HTTP request via Android App

I have a PHP script that will run a set of commands on my Raspberry Pi (such as turning on/off an LED) when opened in the web browser. I want to run this script when a button is pressed in the Android App through onClick() method.

How do I call the HTTP in Android Studio without loading the web page?

It seems like you are new on android or android studio, it is suggested try to Post With Little more Explanation so everyone could understand more properly.
Let's Start
There are couple of libraries in android that make network requests i am going to post some random code and raise some questions for you and provide you some resource and i suggest you to go head and search for them cause they are gonna take your some time, Here is the some random code:
And don't worry if it's in kotlin

interface ApiService {
    @GET("popular")
    suspend fun getApi(
        @Query("query") id: String
    ) : Response<Movie>

companion object RetrofitRequest {

    private val interceptor = Interceptor { chain ->
        val url = chain.request()
                .url()
                .newBuilder()
                .addQueryParameter("access_key", API_KEY)
                .build()

        val request = chain.request().newBuilder().url(url).build()

        return@Interceptor chain.proceed(request)
    }

    private val okHttpClient = OkHttpClient
            .Builder()
            .addInterceptor(interceptor)

            .build()

    @Volatile
    private var instance: ApiService? = null

    fun getInstance(): ApiService = instance ?: synchronized(this) {
        instance ?: fullResponse().also {
            instance = it
        }
    }

    private fun retrofitBuild(): Retrofit =
            Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

    private fun fullResponse(): ApiService {
        return retrofitBuild().create(ApiService::class.java)
    }
}
}

Que.1 -> What is Interceptor?
Que.2 -> What is Okhttp?
Que.3 -> What is Retrofit(Retrofit2)?
Here is some resource:
https://square.github.io/retrofit/
https://androidclarified.com/okhttp-interceptor-retrofit2-example/
Tip: To Learn more about fully furnish Network app, search something like: Retrofit using rxjava(rxjava is framework) or retrofit using kotlin Coroutines(if you plan to use kotlin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM