2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

N・S高等学校Advent Calendar 2021

Day 15

Retrofit2でform-dataにファイルを含む複数の値をPOSTする

Last updated at Posted at 2021-12-16

はじめに

この記事は N・S高等学校 Advent Calendar 2021 の15日目です。

こんにちは。N高生です。空いてたので書きます。

本題

Postmanで言うこれをしたい。

ApiService.kt
interface ApiService {
    @JvmSuppressWildcards
    @POST("upload.php")
    suspend fun upload(@Body body: RequestBody): Response<ResponseBody> // Response<ResponseBody> はよしなに。

    companion object {
        var apiService: ApiService? = null

        fun getInstance(): ApiService {
            if (apiService == null) {
                apiService = Retrofit.Builder()
                    .baseUrl("URL") // TODO: ここにURLを入れる
                    .addConverterFactory(GsonConverterFactory.create())
                    .build().create(ApiService::class.java)
            }
            return apiService!!
        }
    }
}
Activity.kt
val api = ApiService.getInstance()

val file = File(/* TODO: いい感じに */)
val body = file.asRequestBody("application/pdf".toMediaTypeOrNull()) // MIMEはいい感じに変えてください。

val requestBody = MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("file", file.name, body)
    .addFormDataPart("a", "Vintage Culture")
    .addFormDataPart("b", "James Hype")
    .addFormDataPart("c", "Claptone")
    .build()

api.upload(requestBody)

さいごに

N高S高成績確認アプリを作ったのでインストールしてくれると喜びます。

iOS版
Android版



宣伝ヨシッ!

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?