Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在android应用程序上使用kotlin发送带有基本身份验证的帖子_Android_Http_Kotlin_Post_Basic Authentication - Fatal编程技术网

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

如何在android应用程序上使用kotlin发送带有基本身份验证的帖子,android,http,kotlin,post,basic-authentication,Android,Http,Kotlin,Post,Basic Authentication,在此之前,我想提一提的是,如果任何库有助于加快或简化流程,我都可以使用 我需要向端点发送post请求(http://myserver.com/api/data/save)。 正文必须是具有以下结构的json: { “id”:“ABCDE1234”, “日期”:“2021-05-05”, “姓名”:“杰森” } 所以,我需要提出一个post请求。端点需要身份验证,因此我需要合并用户名和密码。在何处以及如何添加它们 致意 在何处以及如何添加它们 有多种方法可以将身份验证详细信息添加到任何API请求

在此之前,我想提一提的是,如果任何库有助于加快或简化流程,我都可以使用

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

{
“id”:“ABCDE1234”,
“日期”:“2021-05-05”,
“姓名”:“杰森”
}
所以,我需要提出一个post请求。端点需要身份验证,因此我需要合并用户名和密码。在何处以及如何添加它们

致意

在何处以及如何添加它们

有多种方法可以将身份验证详细信息添加到任何API请求中。假设您正在使用,实现这一点的理想方法之一就是使用

您需要一个实现
拦截器的类

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接口中,向相应的API添加需要身份验证的标头

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

如果您可以使用该库,那么改型可能是一个不错的选择。通过改装,您可以做到这一点:
val authClient = OkHttpClient.Builder()
    .addInterceptor(AuthInterceptor())
    .build()

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