M.Yogeshwaran M.Yogeshwaran - 2 months ago 12
Android Question

Need help for retrofit login example?

http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/

in this username and password is part of it i need to post the user entered username and password from edittext and getting json response like this

{"Result":"1","UserID":"0"}


how to get that json using retrofit . I have successfully made this with asynctask . But feeling quite difficult to implement through retrofit.
my question is


  • Which is the base url?

  • in interface which should be exposed in post method.

  • How can i get the json response from rest service through json .



Below is my main activity:

package com.example.first.servicefirst;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends Activity {
EditText password,userName;
Button login,resister;
ProgressBar progressbar;
TextView tv;

String url="http://172.16.7.203/sfAppServices/SF_UserLogin.svc/rest/login/";

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.password);

userName=(EditText) findViewById(R.id.txtEmployeeCode);

login=(Button) findViewById(R.id.btnsignin);
userName.setBackgroundResource(R.drawable.colorfoucs);


//progess_msz.setVisibility(View.GONE);
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();

} else {
showAlertDialog(MainActivity.this,"No Network","Please Check Your Network Connectivity",true);
}

final ConnectionDetector cd = new ConnectionDetector(getApplicationContext());

login.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
progressbar = (ProgressBar) findViewById(R.id.progressBar);
progressbar.setVisibility(View.VISIBLE);


login();

}
});


}

public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// Setting Dialog Title
alertDialog.setTitle(title);

// Setting Dialog Message
alertDialog.setMessage(message);

// Setting alert dialog icon


// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});

// Showing Alert Message
alertDialog.show();
}
public void login(){
Retrofit retro = new
Retrofit.Builder().baseUrl("http://172.16.7.203").addConverterFactory(GsonConverterFactory.create()).build();
RetrofitRest retrofitRest = retro.create(RetrofitRest.class);
String s1 = userName.getText().toString();
String s2 = password.getText().toString();
if (s1.equals("")) {
userName.setError("Enter User Name");
}
if (s2.equals("")) {
password.setError("Enter Password");
}

retrofitRest.login(s1,s2, new Callback<ModelLogin>() {
@Override
public void onResponse(Response<ModelLogin> response, Retrofit retrofit) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}

@Override
public void onFailure(Throwable t) {

}
});
}
}


Below is my interface:

public interface RetrofitRest {
@FormUrlEncoded
@POST("/sfAppServices/SF_UserLogin.svc/rest/login/")
Callback<ModelLogin> login(@Query("empcode") String employeecode, @Query("password") String password,
Callback<ModelLogin> callback);
}


My pojo:

package com.example.first.servicefirst;

import com.google.gson.annotations.SerializedName;

public class ModelLogin {

private String empcode;
private ModelLogin(){}
@SerializedName("Result")
private String result;
public String getResult(){
return result;
}
private String password;
public String getEmpcode() {
return empcode;
}


public String getPassword() {
return password;
}

public void setEmpcode(String empcode) {
this.empcode = empcode;
}



public void setPassword(String password) {
this.password = password;
}


}

Answer

Since your request parameters are path parameters you do not need a DTO for your request. Just create a DTO for your response like this.

public class LoginResponseDto {
    @SerializedName("Result")
    private String result;
    @SerializedName("UserID")
    private String userId;

    // Getters & Setters etc.
}

And lets parse your URL and create your service interface. I think your base url will be "http://172.16.7.203/sfAppServices/" and other are for service identification. It highly depends on other services you may want to use. If you are just using login service you can even make your base url like this "http://172.16.7.203/sfAppServices/SF_UserLogin.svc" but these decisions change your service annotations.

public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public void login(@Path("employeeCode") String employeeCode, @Path("password") String password, Callback<LoginResponseDto> callback);
} 

And at last your retrofit instance. You should not create your Retrofit instance over and over again. Instead create it in your application or use a singleton pattern and get LoginService when you need it.

Update

Since you are using Retrofit 2 you should use a service like this.

public interface LoginService{
    @POST("/SF_UserLogin.svc/rest/login/{employeeCode}/{password}") // Assume your base url is http://172.16.7.203/sfAppServices/
    public Call<LoginResponseDto> login(@Path("employeeCode") String employeeCode, @Path("password") String password);
}