繁体   English   中英

如何在 android 应用程序上使用 kotlin 发送具有基本身份验证的 POST

[英]How to send a POST with basic auth using kotlin on an android app

首先,我想提一下,如果它有助于加快或简化流程,我可以使用任何库。

我需要向端点( http://myserver.com/api/data/save )发送一个发布请求。 主体必须是具有以下结构的 json:

{
   "id": "ABCDE1234",
   "date": "2021-05-05",
   "name": "Jason"
}

所以,我需要发出一个帖子请求。 端点需要身份验证,因此我需要合并用户名和密码。 我在哪里以及如何添加它们?

此致

我在哪里以及如何添加它们?

有多种方法可以将您的身份验证详细信息添加到任何 API 请求。 假设您使用的是Retrofit 2 ,实现此目的的理想方法之一是使用OkHttp 拦截器

你需要一个实现Interceptor的 class

class AuthInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()

        // Add auth details here
        if (request.header("Authentication-required") != null) {
            request = request.newBuilder()
                .addHeader("username", "username value")
                .addHeader("password", "password value")
                .build()
        }

        return chain.proceed(request)
    }
}

在您的 API 界面中,将 header 添加到需要身份验证的相应 API

@Headers("Authentication-required")
@POST("/save")
fun doSave(@Body data: PostData): Call<Status>

最后,使用OkHttpClient构建您的 retrofit 客户端

val authClient = OkHttpClient.Builder()
    .addInterceptor(AuthInterceptor())
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl(your_base_url)
    .client(authClient)
    .build()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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