[英]How can I make a HTTP request via Android App
我有一個 PHP 腳本,當在 web 瀏覽器中打開時,它將在我的 Raspberry Pi 上運行一組命令(例如打開/關閉 LED)。 我想通過 onClick() 方法在 Android 應用程序中按下按鈕時運行此腳本。
如何在不加載 web 頁面的情況下在 Android Studio 中調用 HTTP?
看來你是 android 或 android 工作室的新手,建議嘗試發布更多的解釋,以便每個人都能更正確地理解。
開始吧
android 中有幾個庫會發出網絡請求這是一些隨機代碼:
如果它在 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 -> 什么是攔截器?
Que.2 -> 什么是 Okhttp?
Que.3 -> 什么是改造(Retrofit2)?
這是一些資源:
https://square.github.io/retrofit/
https://androidclarified.com/okhttp-interceptor-retrofit2-example/
提示:要了解更多關於完整網絡應用程序的信息,請搜索以下內容:Retrofit 使用 rxjava(rxjava 是框架)或 retrofit 使用 kotlin 協程
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.