Last active
May 5, 2024 11:09
-
-
Save MrNegativeTW/30a13fb44f1cef2d1a79741fef1a61bd to your computer and use it in GitHub Desktop.
Retrofit 2 Kotlin Example, Imgur upload image example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.your.packagename | |
import com.txwstudio.app.roadreport.json.imgurupload.ImgurUploadJson | |
import okhttp3.MultipartBody | |
import okhttp3.OkHttpClient | |
import retrofit2.Call | |
import retrofit2.Retrofit | |
import retrofit2.converter.gson.GsonConverterFactory | |
import retrofit2.http.Header | |
import retrofit2.http.Multipart | |
import retrofit2.http.POST | |
import retrofit2.http.Part | |
import java.util.concurrent.TimeUnit | |
private const val BASE_URL = "https://api.imgur.com" | |
private val okHttpClient = OkHttpClient.Builder() | |
.connectTimeout(15, TimeUnit.SECONDS) | |
.writeTimeout(30, TimeUnit.SECONDS) | |
.readTimeout(15, TimeUnit.SECONDS) | |
.build() | |
private val retrofit = Retrofit.Builder().client(okHttpClient) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.baseUrl(BASE_URL) | |
.build() | |
interface ImgurApiService { | |
/** | |
* Imgur upload API. | |
* | |
* @param clientId Imgur Client ID | |
* @param image The image want to upload | |
*/ | |
@Multipart | |
@POST("/3/upload") | |
fun postImage( | |
@Header("Authorization") clientId: String, | |
@Part image: MultipartBody.Part | |
): | |
Call<ImgurUploadJson> | |
} | |
object ImgurApi { | |
val retrofitService: ImgurApiService by lazy { | |
retrofit.create(ImgurApiService::class.java) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.your.packagename | |
import com.google.gson.annotations.SerializedName | |
data class ImgurUploadJson( | |
@SerializedName("data") val data: Data?, | |
@SerializedName("status") val status: Int?, | |
@SerializedName("success") val success: Boolean? | |
) { | |
fun getImageLink(): String? { | |
return data?.link | |
} | |
} | |
// ---------- | |
// Another kt file | |
// ---------- | |
package com.your.packagename | |
data class Data( | |
val account_id: Int, | |
val account_url: String, | |
val ad_type: Any, | |
val ad_url: Any, | |
val animated: Boolean, | |
val bandwidth: Int, | |
val datetime: Int, | |
val deletehash: String, | |
val description: Any, | |
val favorite: Boolean, | |
val has_sound: Boolean, | |
val height: Int, | |
val hls: String, | |
val id: String, | |
val in_gallery: Boolean, | |
val in_most_viral: Boolean, | |
val is_ad: Boolean, | |
val link: String, | |
val mp4: String, | |
val name: String, | |
val nsfw: Any, | |
val section: Any, | |
val size: Int, | |
val tags: List<Any>, | |
val title: Any, | |
val type: String, | |
val views: Int, | |
val vote: Any, | |
val width: Int | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun sendImageAndGetLink(body: MultipartBody.Part) { | |
val imgurApi = ImgurApi.retrofitService.postImage("YOUR_CLIENT_ID_HERE", body) | |
imgurApi.enqueue(object : Callback<ImgurUploadJson> { | |
override fun onResponse(call: Call<ImgurUploadJson>, response: Response<ImgurUploadJson>) { | |
binding.progressbarEventEditorImageProgress.visibility = View.GONE | |
if (response.isSuccessful) { | |
// Prevent "Error 429 Too many requests", when run into it, the link will be null. | |
if (response.body()?.getImageLink() == null || response.body()?.getImageLink() == "null") { | |
eventEditorViewModel.imageUrl.value = "" | |
Util().snackBarShort( | |
requireActivity().findViewById(R.id.coordinatorLayout_eventEditor), | |
getString(R.string.accidentEvent_imageUploadFail_server) | |
) | |
} else { | |
Log.i("TESTTT", "圖片連結為 " + response.body()?.getImageLink()) | |
eventEditorViewModel.imageUrl.value = response.body()?.getImageLink() | |
} | |
} else { | |
Util().snackBarShort( | |
requireActivity().findViewById(R.id.coordinatorLayout_eventEditor), | |
"Imgur Error ${response.code().toString()}" | |
) | |
} | |
} | |
override fun onFailure(call: Call<ImgurUploadJson>, t: Throwable) { | |
binding.progressbarEventEditorImageProgress.visibility = View.GONE | |
val errMsg: String = when (t) { | |
is SocketTimeoutException -> { | |
getString(R.string.accidentEvent_imageUploadFail_timeout) | |
} | |
is IOException -> { | |
getString(R.string.accidentEvent_imageUploadFail_IO) | |
} | |
else -> getString(R.string.accidentEvent_imageUploadFail_unknown) | |
} | |
Util().snackBarShort( | |
requireActivity().findViewById(R.id.coordinatorLayout_eventEditor), | |
errMsg | |
) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment