remopomposini
3/8/2018 - 9:55 AM

Android http get function

Android http get function

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

        private String urlValue;

        public HttpGet(String urlValue){
            this.urlValue = urlValue;
        }

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {

            try{
                String address = getResources().getString(R.string.url_http_get)+urlValue;
                URL url = new URL(address);
                Log.d("HTTP GET URL", address);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");

                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();*/
            Log.d("HTTP GET response", result);
            parseJsonResponse(result);
        }
    }