 
 카톡
카톡
◎위챗 : speedseoul
 
                https://www.studytutorial.in/android-httpurlconnection-post-and-get-request-tutorial
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 project in Android Studio, goto File ⇒ New ⇒ New Projects.
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 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {        protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {}        @Override        protectedvoidonPostExecute(String result) {}    }} | 
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 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {        protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {                   try{            JSONObject postDataParams = newJSONObject();            postDataParams.put("name", "abc");            postDataParams.put("email", "abc@gmail.com");            Log.e("params",postDataParams.toString());         }         catch(Exception e){             returnnewString("Exception: "+ e.getMessage());         }        }        @Override        protectedvoidonPostExecute(String result) {                   }    }} | 
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 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);           }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {        protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {                   try{            JSONObject postDataParams = newJSONObject();            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){            returnnewString("Exception: "+ e.getMessage());         }        }        @Override        protectedvoidonPostExecute(String result) {}    }} | 
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 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {      try{         protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {                        JSONObject postDataParams = newJSONObject();            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){           returnnewString("Exception: "+ e.getMessage());       }        }        @Override        protectedvoidonPostExecute(String result) {                   }    }    publicString getPostDataString(JSONObject params) throwsException {        StringBuilder result = newStringBuilder();        booleanfirst = 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"));        }        returnresult.toString();    }} | 
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 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);            }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {        protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {          try{            JSONObject postDataParams = newJSONObject();            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 = newBufferedWriter(                        newOutputStreamWriter(os, "UTF-8"));                writer.write(getPostDataString(postDataParams));                writer.flush();                writer.close();                os.close();                intresponseCode=conn.getResponseCode();                if(responseCode == HttpsURLConnection.HTTP_OK) {                    BufferedReader in=newBufferedReader(                               newInputStreamReader(                                 conn.getInputStream()));                    StringBuffer sb = newStringBuffer("");                    String line="";                    while((line = in.readLine()) != null) {                        sb.append(line);                        break;                    }                    in.close();                    returnsb.toString();                }                else{                    returnnewString("false : "+responseCode);                }            }            catch(Exception e){                returnnewString("Exception: "+ e.getMessage());            }        }        @Override        protectedvoidonPostExecute(String result) {           Toast.makeText(getApplicationContext(), result,                    Toast.LENGTH_LONG).show();        }    }    publicString getPostDataString(JSONObject params) throwsException {        StringBuilder result = newStringBuilder();        booleanfirst = 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"));        }        returnresult.toString();    }} | 
Now, we can call the SendPostRequest() method to send and receive data from the server end. here is final MainActivity.java file
| 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 104 105 | publicclassMainActivity extendsAppCompatActivity {       @Override    protectedvoidonCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        newSendPostRequest().execute();            }    publicclassSendPostRequest extendsAsyncTask<String, Void, String> {        protectedvoidonPreExecute(){}        protectedString doInBackground(String... arg0) {          try{            JSONObject postDataParams = newJSONObject();            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 = newBufferedWriter(                        newOutputStreamWriter(os, "UTF-8"));                writer.write(getPostDataString(postDataParams));                writer.flush();                writer.close();                os.close();                intresponseCode=conn.getResponseCode();                if(responseCode == HttpsURLConnection.HTTP_OK) {                    BufferedReader in=newBufferedReader(new                           InputStreamReader(                                  conn.getInputStream()));                    StringBuffer sb = newStringBuffer("");                    String line="";                    while((line = in.readLine()) != null) {                        sb.append(line);                        break;                    }                    in.close();                    returnsb.toString();                }                else{                    returnnewString("false : "+responseCode);                }            }            catch(Exception e){                returnnewString("Exception: "+ e.getMessage());            }        }        @Override        protectedvoidonPostExecute(String result) {           Toast.makeText(getApplicationContext(), result,                    Toast.LENGTH_LONG).show();        }    }    publicString getPostDataString(JSONObject params) throwsException {        StringBuilder result = newStringBuilder();        booleanfirst = 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"));        }        returnresult.toString();    }} | 
Here is the PHP code that gets request from Android Application and return response( To return response, we need to print data).
| 1 2 3 4 5 6 | <?php $email= $_POST['email'];$name= $_POST['name'];print_r(json_encode($_POST));?> | 
