-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFormsparkService.kt
59 lines (47 loc) · 1.92 KB
/
FormsparkService.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
data class ContactResponse(val name: String, val message: String)
interface ApiService {
@POST("your-form-id")
fun contact(@Body data: HashMap<String, Any>): Single<ContactResponse>
}
class FormsparkService {
companion object {
private var instance: ServiceBuilder? = null
private var retrofit: ApiService? = null
private var context: Context? = null
private const val baseURL = "https://submit-form.com/"
fun initialize(context: Context) {
if (instance == null) {
instance = ServiceBuilder()
Companion.context = context
instance!!.initializeRetro()
}
}
fun get(): ApiService {
return retrofit
?: throw IllegalStateException("FormsparkService must be initialized first.")
}
}
private fun initializeRetro() {
retrofit = Retrofit.Builder()
.baseUrl(baseURL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().setLenient().create()))
.client(getOkHttpClient())
.build()
.create(ApiService::class.java)
}
private fun getOkHttpClient(): OkHttpClient {
return OkHttpClient
.Builder()
.connectTimeout(1000, TimeUnit.SECONDS)
.writeTimeout(1000, TimeUnit.SECONDS)
.readTimeout(1000, TimeUnit.SECONDS)
.addInterceptor { chain ->
val requestBuilder: Request.Builder = chain.request().newBuilder()
requestBuilder.header("Content-Type", "application/json")
requestBuilder.header("Accept", "application/json")
chain.proceed(requestBuilder.build())
}.build()
}
}
// Then call: FormsparkService.get().contact(data)