This example shows how to make a POST API Call using Retrofit in Android. Below code uses Java retrofit2 library to execute an HTTP POST REST web service request with Retrofit HTTP client.
build.gradle [Module]
1 2 3 4 5 6 |
dependencies { .. implementation 'com.squareup.retrofit2:retrofit:2.7.1' implementation 'com.squareup.retrofit2:converter-gson:2.7.1' ... } |
RetroClient.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public final class RetroClient { private static final String BASE_URL = "http://aws.amazon.com"; private static Retrofit retrofit = null; private RetroClient() {} public static Retrofit getInstance() { if (retrofit == null) { synchronized(RetroClient.class) { if (retrofit == null) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); } } } return retrofit; } } |
User.java
1 2 3 4 5 6 |
public class User { private String name; private String country; // getters and setters... } |
RetroService.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Map; import in.myapp.model.User; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.POST; public interface RetroService { @POST("/user/create") Call createUser(@Body User user); } |
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); . ... createUser(); //.. } private void createUser() { RetroService retroService = RetroClient.getInstance().create(RetroService.class); User user = new User(); user.setName("Prasanna"); user.setCountry("India"); retroService.createUser(user).execute(); } } |