p2play-app-android/app/src/main/java/org/libre/agosto/p2play/ajax/Client.kt

68 lines
2.1 KiB
Kotlin
Raw Normal View History

2018-08-18 07:04:31 +02:00
package org.libre.agosto.p2play.ajax
import android.util.JsonReader
import android.util.Log
import org.libre.agosto.p2play.ManagerSingleton
import org.libre.agosto.p2play.models.HostModel
import java.io.InputStreamReader
2019-02-24 17:34:12 +01:00
import java.io.Reader
2018-08-18 07:04:31 +02:00
import java.net.HttpURLConnection
import java.net.URL
open class Client {
protected fun _newCon(uri: String, method: String, token: String = ""): HttpURLConnection {
2019-02-18 00:29:52 +01:00
val url = URL("https://${ManagerSingleton.url}/api/v1/$uri")
val con = url.openConnection() as HttpURLConnection
2018-08-18 07:04:31 +02:00
2024-03-20 04:42:26 +01:00
con.setRequestProperty("User-Agent", "P2play/0.5.3")
2018-08-18 07:04:31 +02:00
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
con.setRequestProperty("Accept", "*/*")
if(token != ""){
2019-02-18 00:29:52 +01:00
con.setRequestProperty("Authorization", "Bearer $token")
2018-08-18 07:04:31 +02:00
}
con.requestMethod=method
2019-10-19 21:02:13 +02:00
con.connectTimeout=60000
con.readTimeout=60000
2018-08-18 07:04:31 +02:00
2019-02-18 00:29:52 +01:00
if(method == "POST")
2018-08-18 07:04:31 +02:00
con.doOutput=true
Log.d("Petition", url.toString())
2018-08-18 07:04:31 +02:00
return con
}
fun getKeys():HostModel{
2019-02-18 00:29:52 +01:00
val con = this._newCon("oauth-clients/local","GET")
val keys = HostModel("","")
2018-08-18 07:04:31 +02:00
try {
if (con.responseCode == 200) {
2019-02-18 00:29:52 +01:00
val response = InputStreamReader(con.inputStream)
val data = JsonReader(response)
2018-08-18 07:04:31 +02:00
data.beginObject()
while (data.hasNext()) {
val key = data.nextName()
when (key.toString()) {
"client_id"->{
keys.client_id = data.nextString()
}
"client_secret"->{
keys.client_secret = data.nextString()
}
else->{
data.skipValue()
}
}
}
data.close()
2018-08-18 07:04:31 +02:00
}
} catch(err:Exception){
2019-02-18 00:29:52 +01:00
err.printStackTrace()
2018-08-18 07:04:31 +02:00
}
con.disconnect()
2019-02-18 00:29:52 +01:00
return keys
2018-08-18 07:04:31 +02:00
}
}