Android Webservices | Adroid Restservices APis

Write a internet permission in android manifest File

<?xml version=“1.0” encoding=“utf-8”?>

<manifest xmlns:android=“http://schemas.android.com/apk/res/android”

  package=“com.gantasoft.webservices”>



  <uses-permission android:name=“android.permission.INTERNET” />


  <application

      android:allowBackup=“true”

      android:icon=“@mipmap/ic_launcher”

      android:label=“@string/app_name”

      android:roundIcon=“@mipmap/ic_launcher_round”

      android:supportsRtl=“true”

      android:theme=“@style/AppTheme”>

      <activity android:name=“.MainActivity”>

          <intent-filter>

              <action android:name=“android.intent.action.MAIN” />


              <category android:name=“android.intent.category.LAUNCHER” />

          </intent-filter>

      </activity>

  </application>


</manifest>



Gradle scripts





apply plugin: ‘com.android.application’


android {

  compileSdkVersion 28

  defaultConfig {

      applicationId “com.gantasoft.webservices”

      minSdkVersion 15

      targetSdkVersion 28

      versionCode 1

      versionName “1.0”

      testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”

  }

  buildTypes {

      release {

          minifyEnabled false

          proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’

      }

  }

}


dependencies {

  implementation fileTree(dir: ‘libs’, include: [‘*.jar’])

  implementation ‘com.android.support:appcompat-v7:28.0.0’

  implementation ‘com.android.support.constraint:constraint-layout:1.1.3’

  testImplementation ‘junit:junit:4.12’

  androidTestImplementation ‘com.android.support.test:runner:1.0.2’

  implementation ‘com.google.code.gson:gson:2.2.4’

  androidTestImplementation‘com.android.support.test.espresso:espresso-core:3.0.2’

}

 

  1. Create Xml file Design

<?xml version=“1.0” encoding=“utf-8”?>

<android.support.constraint.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”>

<LinearLayout

  android:layout_width=“match_parent”

  android:layout_height=“match_parent”

  android:orientation=“vertical”>


  <EditText

      android:layout_width=“match_parent”

      android:id=“@+id/et1”

      android:hint=“Enter Name”

      android:layout_height=“wrap_content” />

  <EditText

      android:layout_width=“match_parent”

      android:id=“@+id/et2”

      android:hint=“Enter Num”

      android:layout_height=“wrap_content” />

  <Button

      android:layout_width=“match_parent”

      android:id=“@+id/bt”

      android:text=“Submit”

      android:layout_height=“wrap_content” />




</LinearLayout>



</android.support.constraint.ConstraintLayout>

 

  1. Write activity   MainActivity.java

 

package com.gantasoft.webservices;


import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;


import java.util.concurrent.ExecutionException;


public class MainActivity extends AppCompatActivity {


EditText editText,editText1;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

      editText=findViewById(R.id.et1);

      editText1=findViewById(R.id.et2);


      Button button=findViewById(R.id.bt);

      button.setOnClickListener(new View.OnClickListener() {

          @Override

          public void onClick(View v) {

              saveToServer();

          }

      });


  }


  private String saveToServer() {


      /*ImagesDTO topicDto=getImagesDTO();


      VideoDataHelper createHelper = new VideoDataHelper(MainActivity.this);

      String gurl = “http://lifebix.com/metro/webexample.php”;

      try {

          String gId= createHelper.new CreateTopic(topicDto, gurl).execute().get();

          return gId;


      } catch (InterruptedException e) {

          e.printStackTrace();

      } catch (ExecutionException e) {

          e.printStackTrace();

      }

*/



      UserRegisterDTO user=getDTO();


      RegistrationHelper registrationHelper=new RegistrationHelper(MainActivity.this);

      String gurl=“http://gantasoft.com/Webservices/insert.php”;

      try {

          String gId= registrationHelper.new Example(user, gurl).execute().get();

          return gId;


      } catch (InterruptedException e) {

          e.printStackTrace();

      } catch (ExecutionException e) {

          e.printStackTrace();

      }


      return null;

  }



  private UserRegisterDTO getDTO(){



      // Create aN OBJECT FOR SET THE EDIT TEXT vALUES

      UserRegisterDTO userRegisterDTO=new UserRegisterDTO();

      userRegisterDTO.setUser_name(editText.getText().toString());

      userRegisterDTO.setUser_email(editText1.getText().toString());


      return userRegisterDTO;

  }



}

 

  1. RegistrationHelper.java

 

package com.gantasoft.webservices;


import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;

import android.util.Log;

import android.widget.Toast;


import org.json.JSONObject;


import java.net.URL;


public class RegistrationHelper {

Context context;

UserRegisterDTO userRegisterDTO;

  public RegistrationHelper(Context context) {

      this.context = context;

  }

  String tag=“VideoHelper”;

  public class Example extends AsyncTask<String, Void, String> {

      // Call after onPreExecute method

      URL url;

      UserRegisterDTO userRegisterDTO;

      private ProgressDialog progress;

      String gurl;


      public Example(UserRegisterDTO imagesDTO, String gurl) {

          this.userRegisterDTO = imagesDTO;

          this.gurl = gurl;

      }


      @Override

      protected void onPreExecute() {

          super.onPreExecute();

          progress = new ProgressDialog(context);

          progress.setMessage(“Loading…”);

          progress.show();

      }


      protected String doInBackground(String… urls) {

          String json = “”;

          try {

              System.out.println(“Connection to url ……………..” + gurl);

              url = new URL(gurl);

              JSONObject jsonObject = new JSONObject();

              jsonObject.accumulate(“user_name”, userRegisterDTO.getUser_name());

              jsonObject.accumulate(“user_email”, userRegisterDTO.getUser_name());

               jsonObject.accumulate(“btnName”,“Insert”);

              json = jsonObject.toString();

              System.out.println(“Json topic share is” + json);


          }

          catch (Exception e) {

              e.printStackTrace();

          }


          String result= RestServices.POST(url, json);

          System.out.println(“Response  is” + result);

          return result;

      }

      protected void onPostExecute(String result) {

          super.onPostExecute(result);

          Log.i(tag, “result is ” +result);

          Toast.makeText(context, “Id is ::  ” + result, Toast.LENGTH_SHORT).show();


          progress.dismiss();


      }


  }



}

 

  1. RestServices.java

 

package com.gantasoft.webservices;


import android.util.Log;


import java.io.BufferedInputStream;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.URL;


public class RestServices {

  public static String POST(URL url, String json){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setDoOutput(true);

          conn.setUseCaches(false);

          conn.setFixedLengthStreamingMode(json.getBytes().length);

          conn.setRequestMethod(“POST”);

          conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

          conn.setRequestProperty(“X-Requested-With”, “XMLHttpRequest”);

          // post the request

          OutputStream out = conn.getOutputStream();

          out.write(json.getBytes());

          out.close();


          // handle the response

          inputStream = conn.getInputStream();

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String GET(URL url){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          inputStream = new BufferedInputStream(conn.getInputStream());

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String PUT(URL url, String json){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setDoOutput(true);

          conn.setUseCaches(false);

          conn.setFixedLengthStreamingMode(json.getBytes().length);

          conn.setRequestMethod(“PUT”);

          conn.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);

          conn.setRequestProperty(“X-Requested-With”, “XMLHttpRequest”);

          // post the request

          OutputStream out = conn.getOutputStream();

          out.write(json.getBytes());

          out.close();


          // handle the response

          inputStream = conn.getInputStream();

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  public static String DELETE(URL url){

      InputStream inputStream = null;

      String result = “”;

      HttpURLConnection conn = null;

      try {


          Log.e(“URL”, “> ” + url);

          conn = (HttpURLConnection) url.openConnection();

          conn.setRequestMethod(“DELETE”);

          if(inputStream != null)

              result = convertInputStreamToString(inputStream);

          else

              result = “Did not work!”;


      }

      catch (Exception e) {

          Log.d(“InputStream”, e.getLocalizedMessage());

      }

      return result;

  }

  private static String convertInputStreamToString(InputStream inputStream) throws IOException {

      BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));

      String line = “”;

      String result = “”;

      while((line = bufferedReader.readLine()) != null)

          result += line;

      inputStream.close();

      return result;

  }

}

 

  1. UserRegisterDTO.java

package com.gantasoft.webservices;


public class UserRegisterDTO {

String user_name,user_email;


  public String getUser_name() {

      return user_name;

  }


  public void setUser_name(String user_name) {

      this.user_name = user_name;

  }


  public String getUser_email() {

      return user_email;

  }


  public void setUser_email(String user_email) {

      this.user_email = user_email;

  }

}