Pritish Sawant
Pritish Sawant

Reputation: 11

Retrofit Post request

I want to post user credentials to following url : http://myurl/authenticate

Parameters : login. Type (JSON) username : string password : string

"login":{"username": "JohnDoe","password": "eoDnhoJ" }

If success

{
" r e s u l t " : " S u c c e s s " ,
"response": "Users Session ID"
}

Here is my code

public interface APIService {

    @POST("/authenticate")
    @FormUrlEncoded
    Call<Login> savePost(@Field("username") String username,
                         @Field("password") String password);
}

public class ApiUtils {

    private ApiUtils() {}

    public static final String BASE_URL = "http://myurl/";

    public static APIService getAPIService() {

        return RetrofitClient.getClient(BASE_URL).create(APIService.class);
    }
}

public class Login {

@SerializedName("username")
@Expose
private String username;
@SerializedName("password")
@Expose
private String password;
//getters and setters
}

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;
    }
}

public class LoginActivity extends AppCompatActivity {

    private EditText usernameEditText,passwordEditText;
    private Button button;
    private APIService mAPIService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        usernameEditText=(EditText)findViewById(R.id.username);
        passwordEditText=(EditText)findViewById(R.id.password);
        button=(Button)findViewById(R.id.signup);

        mAPIService = ApiUtils.getAPIService();


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uname=usernameEditText.getText().toString();
                String pass=passwordEditText.getText().toString();
                if(TextUtils.isEmpty(uname)){
                    Toast.makeText(LoginActivity.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(TextUtils.isEmpty(pass)){
                    Toast.makeText(LoginActivity.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(pass.length()<4){
                    Toast.makeText(LoginActivity.this, "Password should be greater than four characters", Toast.LENGTH_SHORT).show();
                    return;
                }

                sendPost(uname, new StringBuilder(uname).reverse().toString());

            }
        });
    }


    public void sendPost(String username, String password) {
        mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.isSuccessful()) {
                    showResponse(response.body().toString());
                    Log.i("Pritish", "post submitted to API." + response.body().toString());
                    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Log.e("Pritish", "Unable to submit post to API.");
            }
        });
    }

    public void showResponse(String response) {
        Log.i("Abbu",response);
    }
}

Whenever i submit username and password i get null values,can some body please help me?And how can iget the sessionId.I tried looking for various egs but i am so confsued right now.

Upvotes: 1

Views: 3924

Answers (4)

jeevashankar
jeevashankar

Reputation: 1498

Step 1: instead of this code

public interface APIService {

    @POST("/authenticate")
    @FormUrlEncoded
    Call<Login> savePost(@Field("username") String username,
                         @Field("password") String password);
}

Use this code:

public interface APIService {

    @POST("/authenticate")
    Call<Login> savePost(@Body RequestBody body);
}

Step 2: instead of this code in LoginActivity

public void sendPost(String username, String password) {
        mAPIService.savePost(username, password).enqueue(new Callback<Login>() {
            @Override
            public void onResponse(Call<Login> call, Response<Login> response) {

                if(response.isSuccessful()) {
                    showResponse(response.body().toString());
                    Log.i("Pritish", "post submitted to API." + response.body().toString());
                    Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Login> call, Throwable t) {
                Log.e("Pritish", "Unable to submit post to API.");
            }
        });
    }

Change to this code :

public void sendPost(String username, String password) {


        HashMap<String, String> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);      
        String strRequestBody = new Gson().toJson(params);

    //create requestbody
        final RequestBody requestBody = RequestBody.create(MediaType.
                parse("application/json"),strRequestBody);

            mAPIService.savePost(requestBody).enqueue(new Callback<Login>() {
                @Override
                public void onResponse(Call<Login> call, Response<Login> response) {

                    if(response.isSuccessful()) {
                        showResponse(response.body().toString());
                        Log.i("Pritish", "post submitted to API." + response.body().toString());
                        Intent intent=new Intent(getApplicationContext(), MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }

                @Override
                public void onFailure(Call<Login> call, Throwable t) {
                    Log.e("Pritish", "Unable to submit post to API.");
                }
            });
        }

Upvotes: 1

Swapnil Kshirsagar
Swapnil Kshirsagar

Reputation: 670

Instead of follwing code

@POST("/authenticate")
@FormUrlEncoded
Call<Login> savePost(@Field("username") String username,
                     @Field("password") String password);

Use this code

@POST("/authenticate")
Call<Login> savePost(@Query("username") String username,
                     @Query("password") String password);

Upvotes: 1

Araju
Araju

Reputation: 549

  1. Add ServiceGenerator class :

    public class ServiceGenerator {
    
    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(BASEURL)
                    .addConverterFactory(ScalarsConverterFactory.create());
    
    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
    public static Retrofit getRetrofit()
    {
        return builder.client(httpClient.build()).build();
    }
    

    }

2.Add interface RetrofitAPI :

 public interface RetrofitApi {
            @POST("/api/v1/user")
            Call<ResponseBody> login(@Body RequestBody loginBody);
    }

3.Add method for login in your manager class :

public void retrofitLogin(JSONObject login, final String tag) {
        RetrofitApi service = ServiceGenerator.createService(RetrofitApi.class);
        Call<ResponseBody> result = service.login(convertJsonToRequestBody(login));
        result.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                retrofitCheckResponse(response, tag);
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                if (t instanceof IOException) {
                    Log.e("retrofit error", "retrofit error");
                    sendErrorRetrofit(mContext.getString(R.string.ERROR), 500, tag);
                }
            }
        });
    }

Method to convert JSONObject to RequestBody :

 private RequestBody convertJsonToRequestBody(JSONObject jsonObject) {
            if (jsonObject != null) {

                return RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
            } else {
                return null;
            }
        }

4.Now call your retrofitLogin method :

JSONObject mLoginParams = new JSONObject();
JSONObject mLoginObj = new JSONObject();
mLoginParams.put("username", uname);   
mLoginParams.put("password", pass);
mLoginObj.put("appType","mobile");
mLoginObj.put("user", mLoginParams);
volleyRequest.retrofitLogin(mLoginObj, "Login");

Upvotes: 0

user5434198
user5434198

Reputation:

Replace your Login class by following

 @SerializedName("result")
    @Expose
    private String rESULT;
    @SerializedName("response")
    @Expose
    private String response;

    public String getRESULT() {
        return rESULT;
    }

    public void setRESULT(String rESULT) {
        this.rESULT = rESULT;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }

Upvotes: 0

Related Questions