Detail Description : http://androidnoteblog.blogspot.in/2017/03/retrofit-library-with-okhttp.html
Step - 1 : App dependency to app level gradle.
compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup:otto:1.3.8'
compile 'com.google.code.gson:gson:2.6.2'
Step - 2 : Add internet permission to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Step - 3 : activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:id="@+id/loginLayout"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/usernameInput" android:hint="Username:" android:text="admin" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/passwordInput" android:hint="Password:" android:text="admin" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/loginButtonPost" android:text="Login - Post" android:layout_gravity="right" android:layout_weight="1" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/loginButtonGet" android:text="Login - Get" android:layout_weight="1" /> </LinearLayout> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="fill_parent" android:layout_below="@id/loginLayout"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/information" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/extraInformation" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" /> </LinearLayout> </RelativeLayout>
Step - 4 : MainActivity.java
import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.text.method.PasswordTransformationMethod;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;import com.squareup.otto.Bus;import com.squareup.otto.Subscribe; public class MainActivity extends AppCompatActivity { private Communicator communicator; private String username, password; private EditText usernameET, passwordET; private Button loginButtonPost, loginButtonGet; private TextView information, extraInformation; private final static String TAG = "MainActivity"; public static Bus bus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); communicator = new Communicator(); usernameET = (EditText)findViewById(R.id.usernameInput); passwordET = (EditText)findViewById(R.id.passwordInput); //This is used to hide the password's EditText characters. So we can avoid the different hint font. passwordET.setTransformationMethod(new PasswordTransformationMethod()); loginButtonPost = (Button)findViewById(R.id.loginButtonPost); loginButtonPost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { username = usernameET.getText().toString(); password = passwordET.getText().toString(); usePost(username, password); } }); loginButtonGet = (Button)findViewById(R.id.loginButtonGet); loginButtonGet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { username = usernameET.getText().toString(); password = passwordET.getText().toString(); useGet(username, password); } }); information = (TextView)findViewById(R.id.information); extraInformation = (TextView)findViewById(R.id.extraInformation); } private void usePost(String username, String password){ communicator.loginPost(username, password); } private void useGet(String username, String password){ communicator.loginGet(username, password); } @Subscribe public void onServerEvent(ServerEvent serverEvent){ Toast.makeText(this, ""+serverEvent.getServerResponse().getMessage(), Toast.LENGTH_SHORT).show(); if(serverEvent.getServerResponse().getUsername() != null){ information.setText("Username: "+serverEvent.getServerResponse().getUsername() + " || Password: "+serverEvent.getServerResponse().getPassword()); } extraInformation.setText("" + serverEvent.getServerResponse().getMessage()); } @Subscribe public void onErrorEvent(ErrorEvent errorEvent){ Toast.makeText(this,""+errorEvent.getErrorMsg(),Toast.LENGTH_SHORT).show(); } @Override public void onResume(){ super.onResume(); BusProvider.getInstance().register(this); } @Override public void onPause(){ super.onPause(); BusProvider.getInstance().unregister(this); } }
Step - 5 : BusProvider.java
import com.squareup.otto.Bus; public class BusProvider { private static final Bus BUS = new Bus(); public static Bus getInstance(){ return BUS; } public BusProvider(){} }
Step - 6 : Communicator.java
import android.util.Log;import okhttp3.OkHttpClient;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Response;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class Communicator { private static final String TAG = "Communicator"; private static final String SERVER_URL = "http://192.168.1.102/retrofit_login/"; //private static final String SERVER_URL = "http://127.0.0.1/retrofit"; public void loginPost(String username, String password){ //Here a logging interceptor is created HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); //The logging interceptor will be added to the http client OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); //The Retrofit builder will have the client attached, in order to get connection logs Retrofit retrofit = new Retrofit.Builder() .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(SERVER_URL) .build(); Interface service = retrofit.create(Interface.class); Call<ServerResponse> call = service.post("login",username,password); call.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { BusProvider.getInstance().post(new ServerEvent(response.body())); Log.e(TAG,"Success"); } @Override public void onFailure(Call<ServerResponse> call, Throwable t) { // handle execution failures like no internet connectivity BusProvider.getInstance().post(new ErrorEvent(-2,t.getMessage())); } }); } public void loginGet(String username, String password){ //Here a logging interceptor is created HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); //The logging interceptor will be added to the http client OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); //The Retrofit builder will have the client attached, in order to get connection logs Retrofit retrofit = new Retrofit.Builder() .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(SERVER_URL) .build(); Interface service = retrofit.create(Interface.class); Call<ServerResponse> call = service.get("login",username,password); call.enqueue(new Callback<ServerResponse>() { @Override public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) { BusProvider.getInstance().post(new ServerEvent(response.body())); Log.e(TAG,"Success"); } @Override public void onFailure(Call<ServerResponse> call, Throwable t) { // handle execution failures like no internet connectivity BusProvider.getInstance().post(new ErrorEvent(-2,t.getMessage())); } }); } }
Step - 7 : ErrorEvent.java
public class ErrorEvent { private int errorCode; private String errorMsg; public ErrorEvent(int errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } }
Step - 8 : Create interface ( Interface.interface )
import retrofit2.Call;import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.GET;import retrofit2.http.POST;import retrofit2.http.Query; public interface Interface { //This method is used for "POST" @FormUrlEncoded @POST("http://192.168.1.102/retrofit_login/login_api.php") Call<ServerResponse> post( @Field("method") String method, @Field("username") String username, @Field("password") String password ); //This method is used for "GET" @GET("http://192.168.1.102/retrofit_login/login_api.php") Call<ServerResponse> get( @Query("method") String method, @Query("username") String username, @Query("password") String password ); }
Step - 9 : ServerEvent.java
public class ServerEvent { private ServerResponse serverResponse; public ServerEvent(ServerResponse serverResponse) { this.serverResponse = serverResponse; } public ServerResponse getServerResponse() { return serverResponse; } public void setServerResponse(ServerResponse serverResponse) { this.serverResponse = serverResponse; } }
Step - 10 : ServerResponse.java
import com.google.gson.annotations.SerializedName; import java.io.Serializable; public class ServerResponse implements Serializable { @SerializedName("returned_username") private String username; @SerializedName("returned_password") private String password; @SerializedName("message") private String message; @SerializedName("response_code") private int responseCode; public ServerResponse(String username, String password, String message, int responseCode){ this.username = username; this.password = password; this.message = message; this.responseCode = responseCode; } public String getUsername() { return username; } public String getPassword() { return password; } public String getMessage() { return message; } }
Step - 11 : Save login_api.php in XAMPP/WAMP root directory.
login_api.php,
<?php //Post Method here if(isset($_POST['method']) == 'login'){ $username = $_POST['username']; $password = $_POST['password']; if($username == "admin" && $password == "admin"){ $response = array('returned_username' => "-admin-", 'returned_password' => "-admin-", 'message' => "Your credentials are so weak [USING_POST]!", 'response_code' => "1"); echo json_encode($response); }else{ $response = array('response_code' => "-1", 'message' => "invalid username or password"); echo json_encode($response); } } //Get Method here else if(isset($_GET['method']) == 'login'){ $username = $_GET['username']; $password = $_GET['password']; if($username == "admin" && $password == "admin"){ $response = array('returned_username' => "=admin=", 'returned_password' => "=admin=", 'message' => "Your credentials are so weak [USING_GET]!", 'response_code' => "1"); echo json_encode($response); }else{ $response = array('response_code' => "-1", 'message' => "invalid username or password"); echo json_encode($response); } } //If no method else{ $response = array('response_code' => "-2", 'message' => "invalid method"); echo json_encode($response); } ?>
22