Skip to content

Instantly share code, notes, and snippets.

@anandrex5
Last active June 22, 2022 05:32
Show Gist options
  • Save anandrex5/86c7a4be05fabe629f7f4c0b37eb7e02 to your computer and use it in GitHub Desktop.
Save anandrex5/86c7a4be05fabe629f7f4c0b37eb7e02 to your computer and use it in GitHub Desktop.
Retrofit by Using PostRetrofit Using Post
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.retropost">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.RetroPost"
tools:targetApi="31">
<activity
android:name=".PostRequest"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
package com.example.retropost; //Step 1 (Convert Request Code/Body Data Json to Pojo)
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class BodyModel {
@SerializedName("address")
@Expose
private String address;
@SerializedName("cityOid")
@Expose
private Integer cityOid;
@SerializedName("countryOid")
@Expose
private Integer countryOid;
@SerializedName("dateOfBirth")
@Expose
private String dateOfBirth;
@SerializedName("email")
@Expose
private String email;
@SerializedName("firstName")
@Expose
private String firstName;
@SerializedName("gender")
@Expose
private String gender;
@SerializedName("imagePath")
@Expose
private String imagePath;
@SerializedName("lastName")
@Expose
private String lastName;
@SerializedName("mobileNo")
@Expose
private String mobileNo;
@SerializedName("nationalityOid")
@Expose
private Integer nationalityOid;
/**
* No args constructor for use in serialization
*
*/
public BodyModel() {
}
/**
*
* @param firstName
* @param lastName
* @param address
* @param gender
* @param imagePath
* @param nationalityOid
* @param dateOfBirth
* @param mobileNo
* @param countryOid
* @param email
* @param cityOid
*/
public BodyModel(String address, Integer cityOid, Integer countryOid, String dateOfBirth, String email, String firstName, String gender, String imagePath, String lastName, String mobileNo, Integer nationalityOid) {
super();
this.address = address;
this.cityOid = cityOid;
this.countryOid = countryOid;
this.dateOfBirth = dateOfBirth;
this.email = email;
this.firstName = firstName;
this.gender = gender;
this.imagePath = imagePath;
this.lastName = lastName;
this.mobileNo = mobileNo;
this.nationalityOid = nationalityOid;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getCityOid() {
return cityOid;
}
public void setCityOid(Integer cityOid) {
this.cityOid = cityOid;
}
public Integer getCountryOid() {
return countryOid;
}
public void setCountryOid(Integer countryOid) {
this.countryOid = countryOid;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public Integer getNationalityOid() {
return nationalityOid;
}
public void setNationalityOid(Integer nationalityOid) {
this.nationalityOid = nationalityOid;
}
}
plugins {
id 'com.android.application'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.retropost"
minSdk 21
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation "androidx.cardview:cardview:1.0.0"
//
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation("com.squareup.okhttp3:logging-interceptor:4.9.3")
}
package com.example.retropost;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
package com.example.retropost; //Step 4 (Interface)
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
public interface PostInterface {
@POST("ns/customer/v2/update")
Call<BodyModel> createPost(@Body BodyModel profileBodyModel);
}
package com.example.retropost; //Step 3
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class PostMethod {
public static Retrofit retrofit;
private static final String BASE_URL = "https://danbro-api-uat.reciproci.com/api/";
public static Retrofit getRetrofitMethod() {
if (retrofit == null) {
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(chain -> {
Request request = chain.request()
.newBuilder()
.addHeader("Content-Type", " application/json")
.addHeader("DEVICE_ID", "5b39185c0342d9f9")
.addHeader("Accept-Language", "EN")
.addHeader("DEVICE_TYPE", "Android")
.addHeader("APP_VERSION", "0.1.37")
.addHeader("COUNTRY", "India")
.addHeader("CITY", "Lucknow")
.addHeader("Authorization", " bearer 4eb99cc9-3844-4a98-a9d1-5617e151ddb7")
.addHeader("GUEST_USER_TOKEN", "sVMLm8ReIVQIkT86mVThKNN2lvE6NY9GSJkf1Ebq1f8=")
.build();
return chain.proceed(request);
})
.build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
package com.example.retropost; //S5
import android.os.Bundle;
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 androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class PostRequest extends AppCompatActivity {
// creating variables for our edittext,
private EditText firstname, lastname, dob, gender, emailid, mobile_number, country, city, home, residence;
// button,text
private Button update_profile;
private TextView response;
BodyModel profileBodyModel = new BodyModel();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_model);
//initializing our views
firstname = findViewById(R.id.editText1);
lastname = findViewById(R.id.editText2);
dob = findViewById(R.id.editText3);
gender = findViewById(R.id.editText4);
emailid = findViewById(R.id.editText5);
mobile_number = findViewById(R.id.editText6);
country = findViewById(R.id.editText7);
city = findViewById(R.id.editText8);
residence = findViewById(R.id.editText9);
home = findViewById(R.id.editText10);
update_profile = findViewById(R.id.update_btn);
//adding on click listener to our button.
update_profile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validateData();
}
});
}
private void updateData() {
profileBodyModel.setFirstName(firstname.getText().toString());
profileBodyModel.setLastName(lastname.getText().toString());
profileBodyModel.setDateOfBirth(dob.getText().toString());
profileBodyModel.setGender(gender.getText().toString());
profileBodyModel.setEmail(emailid.getText().toString());
profileBodyModel.setMobileNo(mobile_number.getText().toString());
profileBodyModel.setCityOid(Integer.valueOf(city.getText().toString()));
profileBodyModel.setCountryOid(Integer.valueOf(country.getText().toString()));
profileBodyModel.setNationalityOid(Integer.valueOf(residence.getText().toString()));
profileBodyModel.setAddress(home.getText().toString());
apiResponse();
}
private void apiResponse() {
PostInterface postInterface = PostMethod.getRetrofitMethod().create(PostInterface.class);
Call<BodyModel> call = postInterface.createPost(profileBodyModel);
call.enqueue(new Callback<BodyModel>() {
@Override
public void onResponse(Call<BodyModel> call, Response<BodyModel> response) {
Log.e("set", "Success"+response.body());
}
@Override
public void onFailure(Call<BodyModel> call, Throwable t) {
}
});
}
private void validateData() {
if (firstname.getText().toString().isEmpty() && lastname.getText().toString().isEmpty()
&& dob.getText().toString().isEmpty() && gender.getText().toString().isEmpty()
&& emailid.getText().toString().isEmpty() && mobile_number.getText().toString().isEmpty()
&& country.getText().toString().isEmpty() && city.getText().toString().isEmpty()
&& home.getText().toString().isEmpty()
&& residence.getText().toString().isEmpty()) {
Toast.makeText(PostRequest.this, "Please fill the data", Toast.LENGTH_SHORT).show();
}else
{
updateData();
}
}
}
package com.example.retropost; //Step 2 (Convert Response Output ,Json to Pojo)
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseModel {
@SerializedName("timestamp")
@Expose
private Long timestamp;
@SerializedName("access_token")
@Expose
private Object accessToken;
@SerializedName("token_type")
@Expose
private Object tokenType;
@SerializedName("refresh_token")
@Expose
private Object refreshToken;
@SerializedName("expires_in")
@Expose
private Object expiresIn;
@SerializedName("scope")
@Expose
private Object scope;
@SerializedName("status")
@Expose
private String status;
@SerializedName("authToken")
@Expose
private Object authToken;
@SerializedName("mobileNumber")
@Expose
private Object mobileNumber;
@SerializedName("profileCompleted")
@Expose
private Integer profileCompleted;
@SerializedName("customer_id")
@Expose
private Object customerId;
@SerializedName("customerTier")
@Expose
private Object customerTier;
@SerializedName("gender")
@Expose
private Object gender;
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public Object getAccessToken() {
return accessToken;
}
public void setAccessToken(Object accessToken) {
this.accessToken = accessToken;
}
public Object getTokenType() {
return tokenType;
}
public void setTokenType(Object tokenType) {
this.tokenType = tokenType;
}
public Object getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(Object refreshToken) {
this.refreshToken = refreshToken;
}
public Object getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Object expiresIn) {
this.expiresIn = expiresIn;
}
public Object getScope() {
return scope;
}
public void setScope(Object scope) {
this.scope = scope;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getAuthToken() {
return authToken;
}
public void setAuthToken(Object authToken) {
this.authToken = authToken;
}
public Object getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(Object mobileNumber) {
this.mobileNumber = mobileNumber;
}
public Integer getProfileCompleted() {
return profileCompleted;
}
public void setProfileCompleted(Integer profileCompleted) {
this.profileCompleted = profileCompleted;
}
public Object getCustomerId() {
return customerId;
}
public void setCustomerId(Object customerId) {
this.customerId = customerId;
}
public Object getCustomerTier() {
return customerTier;
}
public void setCustomerTier(Object customerTier) {
this.customerTier = customerTier;
}
public Object getGender() {
return gender;
}
public void setGender(Object gender) {
this.gender = gender;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment