Api Integration using POST and GET method
In this tutorial, you will learn how to send HTTP Post or Get Request to server using httpurlconnection from Android App.
In this module, You will create a connection between Android App and server at certain period then sending and receiving data request from Android App to server.
Create a new android project:
Create a new android project in Android Studio, go to File ⇒ New ⇒ New Projects.
Creating Asynchronous method
Here we will create an Asynchronous function called SendPostRequest() in MainActivity.java java file and Asynchronous function operates independently of other processes which will execute the process in background.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public class SendPostRequest extends AsyncTask{ protected void onPreExecute(){} protected String doInBackground(String... arg0) {} @Override protected void onPostExecute(String result) {} } }
Creating URL and JSONObject
Now, here we will need to define url in Asynchronous function and also we have to initialize the JSONObject and add your data into JSONObject as a key value pair, as shown below.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public class SendPostRequest extends AsyncTask{ protected void onPreExecute(){} protected String doInBackground(String... arg0) { try{ URL url = new URL("https://studytutorial.in/post.php"); JSONObject postDataParams = new JSONObject(); postDataParams.put("name", "abc"); postDataParams.put("email", "abc@gmail.com"); Log.e("params",postDataParams.toString()); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) { } } }
Creating URL and JSONObject
Now we will use an URLConnection for HTTP used to send or receive data over the cloud and also create a HttpURLConnection by calling URL.openConnection() and It casting the result to HttpURLConnection which is also set the connection timeout, method type and must be configured with setDoInput(true).
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public class SendPostRequest extends AsyncTask{ protected void onPreExecute(){} protected String doInBackground(String... arg0) { try{ URL url = new URL("https://studytutorial.in/post.php"); JSONObject postDataParams = new JSONObject(); postDataParams.put("name", "abc"); postDataParams.put("email", "abc@gmail.com"); Log.e("params",postDataParams.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) {} } }
Creating a method to convert JSONObject to encode url string format
Then we need to make a string return type function which is called as getPostDataString(). This function is useful when encoding a string to be used in a query part of a URL.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public class SendPostRequest extends AsyncTask{ try{ protected void onPreExecute(){} protected String doInBackground(String... arg0) { URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path JSONObject postDataParams = new JSONObject(); postDataParams.put("name", "abc"); postDataParams.put("email", "abc@gmail.com"); Log.e("params",postDataParams.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) { } } public String getPostDataString(JSONObject params) throws Exception { StringBuilder result = new StringBuilder(); boolean first = true; Iterator<String> itr = params.keys(); while(itr.hasNext()){ String key= itr.next(); Object value = params.get(key); if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(value.toString(), "UTF-8")); } return result.toString(); } }
Return the response in onPostExecute()
Next, we will encode the url string of JSONObject and this url string send the server to get the response and we will get the response via getInputStream() so it read the response through StringBuffer object and it will return the response string into onPostExecute() method.
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public class SendPostRequest extends AsyncTask&lt;String, Void, String&gt; { protected void onPreExecute(){} protected String doInBackground(String... arg0) { try { URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path JSONObject postDataParams = new JSONObject(); postDataParams.put("name", "abc"); postDataParams.put("email", "abc@gmail.com"); Log.e("params",postDataParams.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader in=new BufferedReader( new InputStreamReader( conn.getInputStream())); StringBuffer sb = new StringBuffer(""); String line=""; while((line = in.readLine()) != null) { sb.append(line); break; } in.close(); return sb.toString(); } else { return new String("false : "+responseCode); } } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); } } public String getPostDataString(JSONObject params) throws Exception { StringBuilder result = new StringBuilder(); boolean first = true; Iterator itr = params.keys(); while(itr.hasNext()){ String key= itr.next(); Object value = params.get(key); if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(value.toString(), "UTF-8")); } return result.toString(); } }
Call the SendPostRequest() method to Post Request
So, when we will call the SendPostRequest() method to send and receive data from the server end and here is final MainActivity.java file
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new SendPostRequest().execute(); } public class SendPostRequest extends AsyncTask{ protected void onPreExecute(){} protected String doInBackground(String... arg0) { try { URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path JSONObject postDataParams = new JSONObject(); postDataParams.put("name", "abc"); postDataParams.put("email", "abc@gmail.com"); Log.e("params",postDataParams.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { BufferedReader in=new BufferedReader(new InputStreamReader( conn.getInputStream())); StringBuffer sb = new StringBuffer(""); String line=""; while((line = in.readLine()) != null) { sb.append(line); break; } in.close(); return sb.toString(); } else { return new String("false : "+responseCode); } } catch(Exception e){ return new String("Exception: " + e.getMessage()); } } @Override protected void onPostExecute(String result) { Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show(); } } public String getPostDataString(JSONObject params) throws Exception { StringBuilder result = new StringBuilder(); boolean first = true; Iterator itr = params.keys(); while(itr.hasNext()){ String key= itr.next(); Object value = params.get(key); if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(key, "UTF-8")); result.append("="); result.append(URLEncoder.encode(value.toString(), "UTF-8")); } return result.toString(); } }
PHP Backend Code
Here is the PHP code, which can be used for establish connection between server and android app, it gets request from Android app and return response( To return response, we need to print data).