Web Services 如何使用承载令牌连接到Web服务?

2vuwiymt  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(198)

我正在尝试通过使用Retrofit连接到Web服务来提取数据。我将在应用程序中使用的Web服务已加密。因此,我可以使用承载令牌访问它。我还需要续订承载令牌。我确实获得了承载令牌。如何使用获得的此承载令牌连接到Web服务?
Postman :enter image description here
服务API:

interface ServiceAPI {

    @FormUrlEncoded
    @POST("GetToken")
    fun getGetToken(@Field("grant_type")grant_type:String, @Field("username") username:String, @Field("password") password:String):Call<Token>

    @GET("api/Users")
    fun getUsers(@Header("Authorization") authorization: String): Call<UsersModel>

  
}
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        getServiceExample()

    }

fun getServiceExample(){
        val BASE_URL = "https://www.exampleserviceid.com/"
        val api = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()

       

        val service = api.create(ServiceAPI::class.java).getGetToken("password","myusername","mypassword")


        service.enqueue(object : Callback<Token>{
            override fun onResponse(call: Call<Token>, response: Response<Token>) {
                if (response.isSuccessful){

                     val gettoken: Token? = response.body()
                    val token = gettoken?.accessToken  //  This is how I get the Bearer token
                    

                }
            }

            override fun onFailure(call: Call<Token>, t: Throwable) {
                
                TODO("Not yet implemented")

            }

        })

    }

令牌:

class Token : Serializable {
    @SerializedName("access_token")
    @Expose
    var accessToken: String? = null

    @SerializedName("token_type")
    @Expose
    var tokenType: String? = null

    @SerializedName("expires_in")
    @Expose
    var expiresIn: Int? = null

  
    constructor() {}

    /**
     *
     * @param tokenType
     * @param accessToken
     * @param expiresIn
     */
    constructor(accessToken: String?, tokenType: String?, expiresIn: Int?) : super() {
        this.accessToken = accessToken
        this.tokenType = tokenType
        this.expiresIn = expiresIn
    }

}

用户模型:

class UsersModel : Serializable {
    @SerializedName("username")
    @Expose
    var username: String? = null

    @SerializedName("userage")
    @Expose
    var userage: String? = null

 
    constructor() {}

    constructor(username: String?, userage: String?) : super() {
        this.username= username
        this.userage= userage

    }

}

如何使用我获得的此承载令牌连接到Web服务?
更新:

fun getServiceExample(){
        val BASE_URL = "https://www.exampleserviceid.com/"
        val api = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()

       

        val service = api.create(ServiceAPI::class.java).getGetToken("password","myusername","mypassword")


        service.enqueue(object : Callback<Token>{
            override fun onResponse(call: Call<Token>, response: Response<Token>) {
                if (response.isSuccessful){

                     val gettoken: Token? = response.body()
                    val token = gettoken?.accessToken  //  This is how I get the Bearer token

val httpClient: OkHttpClient.Builder =OkHttpClient.Builder()
                        .callTimeout(60, TimeUnit.SECONDS)
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)

                    httpClient.addInterceptor(object: Interceptor {
                        override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
                            val original = chain.request();

                            val request = original.newBuilder()
                                .header("Authorization","Bearer " + token)
                                .method(original.method(), original.body())
                                .build();

                            val Log = Logger.getLogger(MainFragment::class.java.name)
                            Log.warning("Bearer " + token)

                            return chain.proceed(request);
                        }
                    })

                    val client = httpClient.build();
                    val retrofit = Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build();

                    val service2 = retrofit.create(ServiceAPI::class.java).getUsers()

service2.enqueue(object : Callback<UsersModel>{
                        override fun onResponse(call: Call<UsersModel>, response: Response<UsersModel>) {
                            if (response.isSuccessful){

                                val usersmodeltoken: UsersModel? = response.body()
                                val usernametoken = usersmodeltoken?.username

                                Toast.makeText(context, usernametoken, Toast.LENGTH_SHORT).show()

                            }
                        }

                        override fun onFailure(call: Call<UsersModel>, t: Throwable) {

                            /*
                            TODO("Not yet implemented")
                             */

                        }

                    })

                    

                }
            }

            override fun onFailure(call: Call<Token>, t: Throwable) {
                
                TODO("Not yet implemented")

            }

        })

    }
jv2fixgn

jv2fixgn1#

你可以做这样的事

val httpClient:OkHttpClient.Builder = OkHttpClient.Builder()
.callTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS);

httpClient.addInterceptor(object:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
         val original = chain.request();

        val request = original.newBuilder()
            header("Authorization","Bearer " + tokenVariable)
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
}

val client = httpClient.build();

val retrofit = Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

相关问题