وب سرویس ارسال پیامک در Retrofit اندروید
در این مطلب قصد داریم در مورد API ارسال پیامک در رتروفیت اندروید صحبت کنیم
وقتی که از رتروفیت برای برقراری ارتباط با سرور استفاده می کنم کار ما خیلی راحت تر میشه چون نه نیازی به استفاده از asynctask داریم(رتروفیت از asynctask پشتیبانی میکنه) و نه نیازی به parse کردن جیسون یا هر ساختار دیگری…
در این مقاله یاد میگیریم که چطوری با کمک رتروفیت اطلاعاتی را به سرور ارسال کنیم و پاسخ سرور را ثبت کنیم… پس با ما همراه باشید .
ابتدا خط های زیر را در build.gradle مینویسیم.توجه کنید که چون پاسخ این درخواست بصورت یک string است نه بصورت جیسون، ما در اینجا از تبدیل کننده scalar به جای Gson استفاده میکنیم
// رتروفیت compile 'com.squareup.retrofit2:retrofit:2.1.0' // SCALAR Parsing compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
ساختAPIClient برای Retrofit
برای این که بتوانیم با Retrofit کار کنیم باید یک نمونه از روی آن بسازیم. برای راحتی کار کل فرایند ساخت یک نمونه از Retrofit یک کلاس میسازیم به نام APIClient:
public class APIClient { public static Retrofit retrofit=null; public static Retrofit getClient(String url) { if (retrofit==null) { retrofit = new Retrofit.Builder() .baseUrl(url) .addConverterFactory(ScalarsConverterFactory.create()) .build(); } return retrofit; }
یک نمونه از کلاس Retrofit.Builder میسازیم که بعد با استفاده از بتوانیم یک نمونه از کلاس Retrofit بسازیم.تبدیل کننده scalar رو بعنوان converter اضافه میکنیم.
ساخت Client برای سرویس
حالا نوبت آن است که با استفاده از Retrofit اعلام کنیم که سرور جه API یی در اختیار ما قرار میدهد. این کار تقریباً حیاتیترین قسمت کار با Retrofit است. فرض کنید سرویس دهنده ما قرار است سرویسی برای ارسال یک پیامک به یک شماره خاص باشد. ما در Clientی که میسازیم باید این سرویس را به طور کامل برای Retrofit تعریف کنیم.اینترفیسی به نام APIInterface ساخته و متد ارسال پیامک را بدین صورت تعریف میکنیم:
public interface APIInterface { @FormUrlEncoded @POST Call<String> sendSmsByParsgreen( @Field("to") String to, @Field("text") String text, @Url String url, @HeaderMap Map<String, String> parsgreen_signature); }
در این قسمت چون url ما شامل baseurl و url نیست از @FormUrlEncoded استفاده کردیم تا بنوانیم آدرس وب سرویس را بصورت واحد وبدون تقسیم آن به دو قسمت بنویسیم.header نیز که همان امضای دیجیتال است و برای هر کاربر متفاوت است و باید بصورت داینامیک تعریف شود بصورت @HeaderMap Map<String, String> parsgreen_signature نوشتیم تا بتوانیم آن را از کاربر گرفته و وارد درخواست post کنیم.
Activity _main
<ScrollView android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="30dp"> امضای دیجیتال <EditText android:hint="امضا" android:textColorHint="@color/colorPrimaryDark" android:textColor="#111" android:textSize="17dp" android:nextFocusDown="@id/message" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/signature" android:layout_marginBottom="20dp" /> شماره ای که قرار است به آن پیامک ارسال شود// <EditText android:hint="ارسال به" android:textColorHint="@color/colorPrimaryDark" android:textColor="#111" android:textSize="17dp" android:nextFocusDown="@id/sendto" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/message" android:layout_marginBottom="20dp" /> <EditText android:hint="متن" android:textColorHint="@color/colorPrimaryDark" android:textColor="#111" android:nextFocusDown="@id/send" android:textSize="17dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sendto" android:lines="3" android:layout_marginBottom="20dp" /> نمایش پیغام ب سرویس// <TextView android:textColor="#111" android:textSize="17dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:lines="4" android:background="@color/light" android:id="@+id/print" android:layout_gravity="right" android:layout_marginBottom="20dp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="17dp" android:background="@color/colorPrimaryDark" android:textColor="#fff" android:text="ارسال" android:id="@+id/send" android:layout_marginBottom="10dp" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorPrimaryDark" android:textColor="#fff" android:textSize="17dp" android:text="خروج" android:id="@+id/exit" /> </LinearLayout> </ScrollView>
Main_Activity
public class ParsGreenSendByHttp extends AppCompatActivity { EditText parsgreensignature,message,sendto; TextView print; Button send,exit; ProgressDialog progressDialog; //وب سرویس url public static final String PARSGREEN_URL="http://login.parsgreen.com/UrlService/sendSMS.ashx/"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pars_green_send_by_http); initViews(); Listeners(); } private void Listeners() { send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //اگر گوشی به اینترنت متصل بود فیلدهارا ارسال کن if (NetworkUtils.isConnectedToInternet(ParsGreenSendByHttp.this)) { sendSms(sendto.getText().toString() ,message.getText().toString(),"",parsgreensignature.getText().toString()); } else { Toast.makeText(getApplicationContext() ,R.string.network_error, Toast.LENGTH_LONG).show(); } } }); exit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { System.exit(1); } }); //برای تهیه امضا به پنل خود،منوی وب سرویس،امضای دیجیتال مراجعه نمایید. parsgreensignature.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View view, boolean b) { Toast.makeText(getApplicationContext() , R.string.signature, Toast.LENGTH_LONG).show(); } }); } private void initViews() { parsgreensignature= (EditText) findViewById(R.id.signature); message= (EditText) findViewById(R.id.message); sendto= (EditText) findViewById(R.id.sendto); send= (Button) findViewById(R.id.send); exit= (Button) findViewById(R.id.exit); print= (TextView) findViewById(R.id.print); } private void sendSmsByParsgreen(String to,String message,String url,String parsgreen_sign){ if (progressDialog == null) { progressDialog = new ProgressDialog(ParsGreenSendByHttp.this); progressDialog.setMessage(getString(R.string.loadingData)); progressDialog.setCancelable(false); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); } APIInterface apiInterface= APIClient.getClient(PARSGREEN_URL).create(APIInterface.class); Map<String, String> map = new HashMap<>(); //قرار دادن هدر در امضا map.put("signature",parsgreen_sign); Call<String> call=apiInterface.sendSms(message,to,url,map); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, retrofit2.Response<String> response) { if(response.isSuccessful()){ try { if (progressDialog.isShowing()) { progressDialog.dismiss(); progressDialog = null; } } catch (Exception exception) { exception.printStackTrace(); } if (response.body().toString().equals("User_NoCredit")) { Toast.makeText(ParsGreenSendByHttp.this, R.string.user_credit, Toast.LENGTH_SHORT).show(); print.setText(response.body().toString()); }else print.setText(response.body().toString()); }else Toast.makeText(getApplicationContext() , R.string.error, Toast.LENGTH_LONG).show(); } @Override public void onFailure(Call<String> call, Throwable t) { try { } catch (Exception exception) { exception.printStackTrace(); } Toast.makeText(getApplicationContext() , R.string.error, Toast.LENGTH_LONG).show(); print.setText(t.getMessage().toString()); } });
فراخوانی سرویس با Retrofit
APIInterface apiInterface= APIClient.getClient(PARSGREEN_URL).create(APIInterface.class); Call<String> call=apiInterface.sendSmsByParsgreen(message,to,url,map(;