اندروید

آموزش Retrofit 2 در اندروید

آموزش Retrofit 2 در اندروید

آموزش Retrofit 2 در اندروید

سلام دوستان عزیر در این سری از آموزش برنامه نویسی اندروید به آموزش Retrofit 2 در اندروید می پردازیم در آموزش های قبلی از Retrofit استفاده کردیم و در این آموزش نحوه کار با Retrofit 2 HTTP Client قرار میدهیم در ادامه با ما همراه باشید تا نحوه Post کردن اطلاعات با استفاده از این کتابخانه فوق العاده (Retrofit) را یاد گیرید.

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

قند شکن فراموش نشود.

وارد فایل AndroidManifest شده و دسترسی زیر را اضافه کنید.

<uses-permission android:name="android.permission.INTERNET" />

باید یک کلاس Pojo همراه با Annotation درست کنیم تا gson یک مپ از کلیدهای json ما درست کند تا بتوان آنها را پارس کند پس یک فایل به نام Post ایجاد کنید و کدهای زیر را در آن قرار دهید.

package ir.programchi.model;
 
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
 
public class Post {
 
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer 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;
    }
 
    public Integer getUserId() {
        return userId;
    }
 
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
     
    @Override
    public String toString() {
        return "Post{" +
                "title='" + title + '\'' +
                ", body='" + body + '\'' +
                ", userId=" + userId +
                ", id=" + id +
                '}';
    }
}

بعد از اینکار باید یک Instance از Retrofit بسازیم تا عمل Request زدن را ایجاد کند.

یک کلاس به نام RetrofitClient.java ایجاد کنید و کدهای زیر را در آن قرار دهید.

package ir.programchi;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
 
public class RetrofitClient {
 
    private static Retrofit retrofit = null;
 
    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

بعد از اینکار باید APIService را ایجاد کنیم این کلاس شامل متدهای مربوط به درخواست Http سمت سرور است مثل Put , Post و Delete

پس یک فایل به نام APIService.java ایجاد کرده و کدهای زیر را در آن قرار دهید.

package ir.programchi;

import com.chikeandroid.retrofittutorial2.data.model.Post;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
 
public interface APIService {
 
    @POST("/posts")
    @FormUrlEncoded
    Call<Post> savePost(@Field("title") String title,
                        @Field("body") String body,
                        @Field("userId") long userId);
}

کد بالا یکسری از مقادیری را به یک Url خاص Post می کند نام متد را برابر با savePost قرار داده ایم.

در نهایت داده به این آدرس Post می شود

http://jsonplaceholder.typicode.com/posts

ما در حال استفاده از یک Api رایگان برای تست هستیم.

و درنهایت یک کلاس به نام ApiUtils داریم که با فراخوانی آن عمل ارسال Request انجام می شود.

پس یک کلاس به نام ApiUtils.java ایجاد کرده و کدهای زیر را در آن قرار دهید.

package ir.programchi;
 
public class ApiUtils {
 
    private ApiUtils() {}
 
    public static final String BASE_URL = "http://jsonplaceholder.typicode.com/";
 
    public static APIService getAPIService() {
 
        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

تا اینجا هرچیزی که برای Retrofit لازم بوده را ایجاد کرده ایم و قابل استفاده است.

یک لاایه درست کنید و کدهای زیر را در آن قرار دهید (در اینجا لایه ما activity_main.xml است.)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_post"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.chikeandroid.retrofittutorial2.AddEditPostActivity">
 
    <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:text="Programchi.ir :D"/>
    <EditText
            android:id="@+id/et_title"
            android:layout_marginTop="18dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_title"/>
 
    <EditText
            android:id="@+id/et_body"
            android:lines="4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_body"/>
 
    <Button
            android:id="@+id/btn_submit"
            android:layout_marginTop="18dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:textColor="@android:color/white"
            android:text="@string/action_submit"/>
 
    <TextView
            android:id="@+id/tv_response"
            android:layout_marginTop="35dp"
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
     
</LinearLayout>

و در نهایت کد زیر را در ManiActivity.java قرار میدهیم.

private TextView mResponseTv;
private APIService mAPIService;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
 
    final EditText titleEt = (EditText) findViewById(R.id.et_title);
    final EditText bodyEt = (EditText) findViewById(R.id.et_body);
    Button submitBtn = (Button) findViewById(R.id.btn_submit);
    mResponseTv = (TextView) findViewById(R.id.tv_response);
 
    mAPIService = ApiUtils.getAPIService();
 
    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String title = titleEt.getText().toString().trim();
            String body = bodyEt.getText().toString().trim();
            if(!TextUtils.isEmpty(title) && !TextUtils.isEmpty(body)) {
                sendPost(title, body);
            }
        }
    });
}
public void sendPost(String title, String body) {
mAPIService.savePost(title, body, 1).enqueue(new Callback<Post>() {
    @Override
    public void onResponse(Call<Post> call, Response<Post> response) {
 
        if(response.isSuccessful()) {
            showResponse(response.body().toString());
            Log.i(TAG, "post submitted to API." + response.body().toString());
        }
    }
 
    @Override
    public void onFailure(Call<Post> call, Throwable t) {
        Log.e(TAG, "Unable to submit post to API.");
    }
});
}
 
public void showResponse(String response) {
    if(mResponseTv.getVisibility() == View.GONE) {
        mResponseTv.setVisibility(View.VISIBLE);
    }
    mResponseTv.setText(response);
}

این آموزش هم به پایان رسید.

موفق و پیروز باشید.

درباره محمد محسن خاشعی نژاد

بیش از ۱۰ سال است که به عنوان مدرس در حوزه های مختلف ICT فعالیت دارم و همیشه در حال یادگیری و یاد دادن هستم.

دیدگاهتان را بنویسید