Android Short Codes

Android Working With HTTP

android http php mysql
Written by Yasir Ameen

Some times we create app which connects and communicates with a web server, android app make request and get result as response. Communication between client(Android) with web server is make using HTTP. Hyper Text Type Protocol is work as a medium used by the client and web server. In this tutorial i will show you, how you can create custom HTTP Handler using Android built-in classes.

I tried to show you the meaning of Android  client and server communication by the image below.

HTTP

You will create two classes for handling your HTTP requests.

  • HttpManager – class will handle HTTP Methods like GET and POST
  • RequestPackage – class will help you to add parameters in your request

 

Writing HttpManager Class

I am going to create a class HttpManager.java class, this class will handle HTTP request using GET and POST Methods. HttpManager class will expose getResponse() Method which will return raw String.

 public class HttpManager {

    public static String getResponse(RequestPackage p) {

        BufferedReader reader = null;
        String uri = p.getUri();
        
        //Managing GET request using appending parameter to the url
        if(p.getMethod().equals("GET")) {

            uri += "?" + p.getEncodedParams();
        }

        try {

            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod(p.getMethod());

            //Managing POST request using OutPutStream
            if (p.getMethod().equals("POST")) {
                con.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
                writer.write(p.getEncodedParams());
                writer.flush();
            }

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }
            return sb.toString();
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                }
                catch (IOException ex) {
                    ex.printStackTrace();
                    return null;
                }
            }
        }

    }
}

 

Writing RequestPackage Class

Most of the webservices expects parameters. We need to know how to send values/parameters to webserver and then webserver process request against the values/parameters received by the client. The RequestPackage.java class will be used to handle such requests.

  public class RequestPackage {

    private String uri;
    private String method = "GET";
    private Map<String,String> params = new HashMap<>();

    public Map<String, Integer> getParamsInt() {
        return paramsInt;
    }

    public void setParamsInt(Map<String, Integer> paramsInt) {
        this.paramsInt = paramsInt;
    }

    private Map<String,Integer> paramsInt = new HashMap<>();

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public Map<String, String> getParams() {
        return params;
    }

    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public void setParams(String key, String value) {
        params.put(key,value);
    }
    
    
    public String getEncodedParams() {
        StringBuilder sb = new StringBuilder();
        for(String key : params.keySet()) {
            String value = null;

            try{
                value = URLEncoder.encode(params.get(key),"UTF-8");
            }
            catch(UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if(sb.length() > 0)
            {
                sb.append("&");
            }

            sb.append(key + "=" + value);
        }
        return sb.toString();
    }
    
}

 

Using HttpManager and RequestPackage Class

You can use these classes for making HTTP request in your app using AsynTask. You can learn about AsyncTask from my post Android AsyncTask With Progress Dialog Post. Keep in mind that, i am writing a generalize code snippet in my MainActivity.java, you can use according to your need.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //========================================================
        //For POST request, parameter pass through the body.
        RequestPackage loginPackage = new RequestPackage();
        loginPackage.setMethod("POST");
        loginPackage.setParams("user","yasirameen");
        loginPackage.setParams("pass","admin123@");
        loginPackage.setUri("http://localhost/restaurant/user_login.php");

        webTask logintask = new webTask();
        logintask.execute(loginPackage);
        //=============================================================


        //=============================================================
        //For GET request parameter pass through the url.
        RequestPackage regPackage = new RequestPackage();
        regPackage.setMethod("GET");
        regPackage.setParams("username","yasirameen");
        regPackage.setParams("email","yasirameen92@gmail.com");
        regPackage.setParams("password","admin123@");
        regPackage.setParams("mobile","923331234567");
        regPackage.setUri("http://localhost/restaurant/user_registration.php");

        webTask regtask = new webTask();
        regtask.execute(regPackage);
        //=============================================================

    }

    public class webTask extends AsyncTask<RequestPackage,String,String> {

        @Override
        protected void onPreExecute() {

            //You can also use progress dialog here
            Toast.makeText(getApplicationContext(), "Please Wait", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected String doInBackground(RequestPackage... requestPackages) {

            String content = HttpManager.getResponse(requestPackages[0]);
            return content;
        }

        @Override
        protected void onPostExecute(String result) {

            //Webserver will return response in a result variable.
            String response = result;
            Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
        }
    }
}

 

In my next article, I will show you, how we can use this technique further to create Login System using PHP MYSQL PDO.

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

Leave a Comment