https://www.studytutorial.in/android-httpurlconnection-post-and-get-request-tutorial



In this tutorial, we will learn how to send HTTP Post Request to server using httpurlconnection from Android App.

Introduction

We will create a connection between Android App and server at certain period then send or receive the data request from Android App to server.



Create a new poject

Create a new project in Android Studio, goto File ⇒ New ⇒ New Projects.

 

Creating Asynchronous method

We will create a Asynchronous method called as SendPostRequest() in MainActivity.java file. Asynchronous method operates independently of other processes. It will execute the process in background.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MainActivity extends AppCompatActivity {
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public class SendPostRequest extends AsyncTask<String, Void, String> {
 
        protected void onPreExecute(){}
 
        protected String doInBackground(String... arg0) {}
 
        @Override
        protected void onPostExecute(String result) {}
    }
}

 

Creating URL and JSONObject

Now, we need to define url in Asynchronous method and also we will initialize the JSONObject and add your data into JSONObject as a key value pair.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class MainActivity extends AppCompatActivity {
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public class SendPostRequest extends AsyncTask<String, Void, String> {
 
        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

We will use an URLConnection for HTTP used to send and receive data over the web and also create a HttpURLConnectionn by calling URL.openConnection() and casting the result to HttpURLConnection and also set the connection timeout, method type and must be configured with setDoInput(true).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class MainActivity extends AppCompatActivity {
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
    }
 
    public class SendPostRequest extends AsyncTask<String, Void, String> {
 
        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

We need to make a string return type method called as getPostDataString(). This method is convenient when encoding a string to be used in a query part of a URL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class MainActivity extends AppCompatActivity {
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public class SendPostRequest extends AsyncTask<String, Void, String> {
      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()

Firstly, we will encode the url string of JSONObject. This url string send the server to get the response. we get the response via getInputStream(). And read the response through StringBuffer object. Return the response string into onPostExcute() method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
public class MainActivity extends AppCompatActivity {
    
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
    }
 
    public class SendPostRequest extends AsyncTask<String, Void, String> {
 
        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) {
 
        &