改造多个POST请求

时间:2018-06-20 08:34:14

标签: java kotlin retrofit2 okhttp3

我是这个库的新手,并在我们项目的其余API中对其进行了尝试,并且效果很好。

现在我正在尝试基于ArrayList项目在循环内创建POST请求,这可能吗?还是有更好的方法?

以下是我的一些代码,可帮助您了解自己的想法

MContacts.tk

  data class MContacts(val name:Sting,val contact:String,val address:String){ 
    companion object {
      val name = "name"
      val contact = "contact"
      val address = "address"
    }
  }

ApiUtils

object ApiUtils {
    val BASE_URL = "http://api.link.com/"
    fun getSOService(): ApiService {
        return RetrofitClient.getClient(BASE_URL).create(ApiService::class.java)
    }
}

RetrofitClient

object RetrofitClient {

    private var retrofit: Retrofit? = null

    fun getClient(baseUrl: String): Retrofit {
        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
        }
        return retrofit!!
    }
}

ApiService

interface ApiService {
    @POST("api/postcontact")
    @FormUrlEncoded
    fun postContact(
            @Field("name") name:String,
            @Field("contact") contact:String
            @Field("address") address:String
            )
            :Call<ContactResponse>
}

活动

var listContacts : ArrayList<MContacts> = ArrayList()
var btnPost:Button? = null
private var mService: ApiService? = null

override fun onCreate(..){


   mService = ApiUtils.getSOService()

   btnPost = find<Button>(R.id.btnPost)

   listContacts.add(MContacts("name-abc","98765632","address 1"))
   listContacts.add(MContacts("name-ab1","9876562","address 2"))
   listContacts.add(MContacts("name-bs","9876465","address 3"))
   listContacts.add(MContacts("name-df","98876356","address 4"))
   listContacts.add(MContacts("name-da","9876533","address 5"))


   btnPost.setOnClickListener{
      //in here my question begins on how can i post all of the listContacts items
      // is ok to make just make a loop of post request like this ?

      for(i in 0 until listContacts.size){
       postnow(
              listContacts.get(i).name,
              listContacts.get(i).contact,
              listContacts.get(i).address )
      }

   } 
}

POST功能

fun postnow(name:String,contact:String,address:String){

   mService!!.postContact(  name ,  contact,   address  ).enqueue(object : Callback<LoginResponse> {
              override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {

               if (response.isSuccessful()) { 

               } else {

               }
            }

              override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                   Log.d("app", "error loading from API")
                 }
            })
}

感谢您的帮助。提供您的更正,评论和建议

0 个答案:

没有答案