Send Post Request With Params Using Retrofit
Solution 1:
build.gradle
compile'com.google.code.gson:gson:2.6.2'compile'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Login APi Put Two Parameters
{"UserId":"1234","Password":"1234"}
Login Response
{"UserId":"1234","FirstName":"Keshav","LastName":"Gera","ProfilePicture":"312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
classAPIClient {
publicstaticfinalStringBASE_URL="Your Base Url ";
privatestaticRetrofitretrofit=null;
publicstatic Retrofit getClient() {
if (retrofit == null) {
retrofit = newRetrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface interface
interfaceAPIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
Login Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
publicclassLoginResponse {
@SerializedName("UserId")
publicStringUserId;
@SerializedName("FirstName")
publicStringFirstName;
@SerializedName("LastName")
publicStringLastName;
@SerializedName("ProfilePicture")
publicStringProfilePicture;
@SerializedName("Password")
publicStringPassword;
@SerializedName("ResponseCode")
publicStringResponseCode;
@SerializedName("ResponseMessage")
publicStringResponseMessage;
publicLoginResponse(StringUserId, StringPassword) {
this.UserId = UserId;
this.Password = Password;
}
publicStringgetUserId() {
returnUserId;
}
publicStringgetFirstName() {
returnFirstName;
}
publicStringgetLastName() {
returnLastName;
}
publicStringgetProfilePicture() {
returnProfilePicture;
}
publicStringgetResponseCode() {
returnResponseCode;
}
publicStringgetResponseMessage() {
returnResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
publicclassMainActivityextendsAppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
privatevoidloginRetrofit2Api(String userId, String password) {
finalLoginResponselogin=newLoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(newCallback<LoginResponse>() {
@OverridepublicvoidonResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponseloginResponse= response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
StringresponseCode= loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@OverridepublicvoidonFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
publicbooleancheckValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
returnfalse;
} elseif (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
returnfalse;
}
returntrue;
}
}
CommonMethod.java
publicclassCommonMethod {
publicstaticfinalStringDISPLAY_MESSAGE_ACTION="com.codecube.broking.gcm";
publicstaticfinalStringEXTRA_MESSAGE="message";
publicstaticbooleanisNetworkAvailable(Context ctx) {
ConnectivityManagerconnectivityManager= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoactiveNetworkInfo= connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
publicstaticvoidshowAlert(String message, Activity context) {
final AlertDialog.Builderbuilder=newAlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", newDialogInterface.OnClickListener() {
publicvoidonClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayoutandroid:layout_width="wrap_content"android:layout_height="match_parent"android:focusable="true"android:focusableInTouchMode="true"android:orientation="vertical"xmlns:android="http://schemas.android.com/apk/res/android"><ImageViewandroid:id="@+id/imgLogin"android:layout_width="200dp"android:layout_height="150dp"android:layout_gravity="center"android:layout_marginTop="20dp"android:padding="5dp"android:background="@mipmap/ic_launcher_round"
/><TextViewandroid:id="@+id/txtLogo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/imgLogin"android:layout_centerHorizontal="true"android:text="Holostik Track and Trace"android:textSize="20dp"android:visibility="gone" /><android.support.design.widget.TextInputLayoutandroid:id="@+id/textInputLayout1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginLeft="@dimen/box_layout_margin_left"android:layout_marginRight="@dimen/box_layout_margin_right"android:layout_marginTop="8dp"android:padding="@dimen/text_input_padding"><EditTextandroid:id="@+id/edtEmail"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="5dp"android:ems="10"android:fontFamily="sans-serif"android:gravity="top"android:hint="Login ID"android:maxLines="10"android:paddingLeft="@dimen/edit_input_padding"android:paddingRight="@dimen/edit_input_padding"android:paddingTop="@dimen/edit_input_padding"android:singleLine="true"></EditText></android.support.design.widget.TextInputLayout><android.support.design.widget.TextInputLayoutandroid:id="@+id/textInputLayout2"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_below="@+id/textInputLayout1"android:layout_marginLeft="@dimen/box_layout_margin_left"android:layout_marginRight="@dimen/box_layout_margin_right"android:padding="@dimen/text_input_padding"><EditTextandroid:id="@+id/edtPass"android:layout_width="match_parent"android:layout_height="wrap_content"android:focusable="true"android:fontFamily="sans-serif"android:hint="Password"android:inputType="textPassword"android:singleLine="true" /></android.support.design.widget.TextInputLayout><RelativeLayoutandroid:id="@+id/rel12"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textInputLayout2"android:layout_marginTop="10dp"android:layout_marginLeft="10dp"
><Buttonandroid:id="@+id/loginSub"android:layout_width="wrap_content"android:layout_height="45dp"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:background="@drawable/border_button"android:paddingLeft="30dp"android:paddingRight="30dp"android:layout_marginRight="10dp"android:text="Login"android:textColor="#ffffff" /></RelativeLayout></LinearLayout>
Solution 2:
This is a simple solution where we do not need to use JSON
publicinterfaceRegisterAPI {
@FormUrlEncoded@POST("/RetrofitExample/insert.php")
public void insertUser(
@Field("name") String name,
@Field("username") String username,
@Field("password") String password,
@Field("email") String email,
Callback<Response> callback);
}
method to send data
privatevoidinsertUser(){
//Here we will handle the http request to insert user to mysql db//Creating a RestAdapterRestAdapteradapter=newRestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter//Creating object for our interfaceRegisterAPIapi= adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
editTextName.getText().toString(),
editTextUsername.getText().toString(),
editTextPassword.getText().toString(),
editTextEmail.getText().toString(),
//Creating an anonymous callbacknewCallback<Response>() {
@Overridepublicvoidsuccess(Response result, Response response) {
//On success we will read the server's output using bufferedreader//Creating a bufferedreader objectBufferedReaderreader=null;
//An string to store output from the serverStringoutput="";
try {
//Initializing buffered reader
reader = newBufferedReader(newInputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
@Overridepublicvoidfailure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
}
}
);
}
Now we can get the post request using php aur any other server side scripting.
Source Android Retrofit Tutorial
Solution 3:
I have found the solution. The issue was a problem in my classes structure. So i updated them like the following samples.
publicclassLandingPageReport{
private ArrayList<LandingPageReportItem> GetDetailWithMonthWithCodeResult;
// + Getter Setter methods
}
publicclassLandingPageReportItem{
privateString code;
privateString field1;
// + Getter Setter methods
}
And then i use this retrofit configuration
@POST("/GetDetailWithMonthWithCode")
void getLandingPageReport(@Field("code") String code,
@Field("monthact") String monthact,
Callback<LandingPageReport> cb);
Solution 4:
You should create an interface for that like it is working well
publicinterfaceService {
@FormUrlEncoded@POST("v1/EmergencyRequirement.php/?op=addPatient")
Call<Result> addPerson(@Field("BloodGroup") String bloodgroup,
@Field("Address") String Address,
@Field("City") String city, @Field("ContactNumber") String contactnumber,
@Field("PatientName") String name,
@Field("Time") String Time, @Field("DonatedBy") String donar);
}
or you can visit to http://teachmeandroidhub.blogspot.com/2018/08/post-data-using-retrofit-in-android.html
and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit
Solution 5:
The good way in my opinion is to send it in the POST Body
this means you'll have a create a new POJO but some might like this implementation the most.
publicinterfaceAPIInterface {
@POST("/GetDetailWithMonthWithCode")
List<LandingPageReport> getLandingPageReport(@Body Report report);
}
Then make your POJO with a constructor, getters and setters.
publicstaticclassReport {
privateString code;
privateString monthact;
publicReport(String code, String monthact) {
this.code = code;
this.monthact = monthact;
}
// Getters and Setters...
}
And just call it the normal way.
Call<List<Report>> request = apiInterface
.createRetrofitAPIInterface()
.getLandingPageReport(new Report(code, monthact));
Post a Comment for "Send Post Request With Params Using Retrofit"