Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Solicitud de autorización POST a Spotify Api con Retrofit

Estoy tratando de usar la API de Spotify. Pero como el token de autenticación dado caduca cada hora, tengo que enviar una solicitud a la API para obtener uno nuevo. Encontré un código en el sitio web oficial que muestra cómo hacerlo.

 var client_id = 'CLIENT_ID'; var client_secret = 'CLIENT_SECRET'; var authOptions = { url: 'https://accounts.spotify.com/api/token', headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, form: { grant_type: 'client_credentials' }, json: true }; request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var token = body.access_token; } });

Pero soy nuevo en la actualización y no conozco ningún js. Entonces no sé cómo puedo convertir este código a kotlin. ¿Puede alguien ayudarme?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Paso 1: Cree una interfaz llamada ApiInterface.kt.

 interface ApiInterface { @POST("token") fun getToken(): Call<ResponseBody> }

Paso 2: En tu actividad pega estas funciones

 public static Retrofit getClient(final String token) { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor) .addInterceptor(new NetInterceptor()) .addInterceptor(chain -> { Request newRequest = chain.request().newBuilder() .addHeader("Authorization", "Basic " + getBasicAuth(clientId, clientServer)) .build(); return chain.proceed(newRequest); }) //.followRedirects(false) //.followSslRedirects(false) .connectTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build(); return new Retrofit.Builder() .baseUrl(url) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build(); }

convertir autenticación básica a base64

 private fun getBasicAuth(client_id: String, client_secret: String): String { val data = ("$client_id:$client_secret").toByteArray(StandardCharsets.UTF_8) return Base64.encodeToString(data, Base64.DEFAULT) }

Paso : 3 Hacer una llamada api

 private fun apiCall() { val call = getClient()!!.create(ApiInterface::class.java).getToken() call.enqueue(object : Callback<UserResponse> { override fun onResponse(call: Call<UserResponse>, response: Response<UserResponse>) { Toast.makeText(this@MainActivity, response.code().toString() + " " + response.body().toString(), Toast.LENGTH_SHORT).show() } override fun onFailure(call: Call<UserResponse>, t: Throwable) { Toast.makeText(this@MainActivity, t.localizedMessage!!.toString(), Toast.LENGTH_SHORT).show() } }) }

Paso 4: llama a api en tu método onCreate().

 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) apiCall() }
about 4 years ago · Juan Pablo Isaza Report

0

después de muchas horas de investigación, pude averiguarlo. aquí está la interfaz:

 @POST("api/token") @FormUrlEncoded fun getToken( @Header("Authorization") auth: String, @Header("Content-Type") content: String, @Field(("grant_type")) grantType: String ): Call<Token>

aquí está la actividad:

 private fun getToken(id:String) { val retrofit: Retrofit = Retrofit.Builder().baseUrl(TOKEN_URL) .addConverterFactory(GsonConverterFactory.create()).build() val service : TopTrackApi = retrofit.create(TopTrackApi::class.java) val base64String = "Basic "+ get64BaseString("$clientID:$clientSECRET") val listCall : Call<Token> = service.getToken(base64String,"application/x-www-form-urlencoded","client_credentials") listCall.enqueue(object : Callback<Token> { override fun onResponse(response: Response<Token>?, retrofit: Retrofit?) { if (response?.body() != null) { setUpRV(id,response.body().access_token) } if(response?.body() == null){ Log.i("Response!", "null response body /getToken") } } override fun onFailure(t: Throwable?) { Log.e("Error", t!!.message.toString()) } }) } fun get64BaseString(value:String):String{ return Base64.encodeToString(value.toByteArray(), Base64.NO_WRAP) }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!