1) 在应用程序的build.gradle中实现这一依赖关系
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
2) 创建APIClient.java类,把这段代码放到该类中。
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class APIClient {
private static Retrofit retrofit = null;
public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(180, TimeUnit.SECONDS)
.writeTimeout(180,TimeUnit.SECONDS)
.connectTimeout(180, TimeUnit.SECONDS)
.build();
public static Retrofit getClient() {
return new Retrofit.Builder()
.baseUrl("http://BASE_URL_HERE/")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
BASE URL是你的服务器主机名。例如,你有apis。所有的apis都以http://localhost:8080/api/.这将是BASE URL。因为所有的api都以这个网址开始。
3) 创建ApiInterface.java接口文件,并在该文件中插入这段代码。
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface ApiInterface {
@POST("insert-multiple-selection")
Call<YOUR_RESPONSE_CLASS> acceptOrder(@Body ArrayList<String> selections);
4) 在你的按钮onclick方法中加入这段代码。
ApiInterface apiInterface= APIClient.getClient().create(ApiInterface.class);
ArrayList<String> selections=new ArrayList<>();
// To add value
selections.add("YOUR_VALUE_1");
selections.add("YOUR_VALUE_2");
selections.add("YOUR_VALUE_3");
// To remove value
selections.remove("YOUR_VALUE_1");
Call<YOUR_RESPONSE_CLASS> call=apiInterface.sendSelections(selections);
call.enqueue(new Callback<YOUR_RESPONSE_CLASS>() {
@Override
public void onResponse(Call<YOUR_RESPONSE_CLASS> call, Response<YOUR_RESPONSE_CLASS> response) {
if(response.isSuccessful()){
Toast.makeText(context, "Successfully sent!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Error code: "+response.code(), Toast.LENGTH_SHORT).show();
@Override