retrofit implementation
dependencies {
implementation "com.google.code.gson:gson:2.8.7"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
}
retrofit implementation
dependencies {
implementation "com.google.code.gson:gson:2.8.7"
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
}
kotlin and retrofit
- intoduction
1. post is used to send data to server
- exapmle
"simple post"
@POST("posts")
Call<Post> createPost(@Body Post post);
"post with from url encoded "
@FormUrlEncoded
@POST("posts")
Call<Post> createPost( @Field("userId") int userid ,
@Field("title") String title,
@Field("body") String body );
"using map"
@FormUrlEncoded
@POST("posts")
Call<Post> createPost(@FieldMap Map<String,String> postMap);
- INTERFACE
public interface MyWebService {
String BASE_URL = "https://jsonplaceholder.typicode.com/";
String FEED = "posts";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
@GET(FEED)
Call<List<Post>> getPosts();
}
- MODEL CLASS
public class Post {
private int userId;
private int id;
private String title;
private String body;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
- IN ACTIVITY WHERE TO SEND POST REQUEST
Post post = new Post(1,"Post Title","this is post body");
Map<String,String> postmap = new HashMap<>();
postmap.put("userId","33");
postmap.put("title","My post title");
postmap.put("body","this is my post body in the map");
Call<Post> postCall = myWebService.createPost(postmap);
postCall.enqueue(new Callback<Post>() {
@Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()){
textView.setText(String.valueOf(response.code()));
show(response.body());
}
}
@Override
public void onFailure(Call<Post> call, Throwable t) {
}
});
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us