Wednesday, November 12, 2014

Android Httpclient and HttpUrlConnection Tutorial


In Most of network-connected Android apps uses HTTP to send &receive data. 
Android includes two HTTP clients: HttpUrlConnection and Apache HttpClient. Both support HTTPS, streaming uploads and downloads, configurable timeouts, connection pooling. as per google devloper doc( http://android-developers.blogspot.com/2011/09/androids-http-clients.html) recommend using HttpUrlConnection for applications targeted at Gingerbread and higher.and google is  spending more time on this ,they are not working much more on ApacheHttpclient.According there document Api level less than  Gingerbread better to use Foriyo.

 From programming point of view, Apache HttpClient is much easier to use and simple methods. But as Google says, due to difficulties with backward compatibility, they cannot improve this class and instead put all efforts in improving HUC (abbr. for HttpURLConnection).
HttpURLConnection is reduce network usage&improve speed and save batter

Before going to explain HttpUrlConnection i will explain what is POST and GET Method.


Post: Post requests supply additional data from the client (browser or app) to the server in the message body it is very secure and difficult to hack.


Get: Get request supply information from the client (browser or app) to the server in the String in URL it is not secure & easy to hack.

HTTPUrlConnection Post .

 public void post()
{
    try
    {
        // Defined URL  where to send data
        URL url = new URL("http://
androidtechi.com/media/webservice/httppost.php");

        // Send POST data request
        String data="parameters";
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write( data );
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new     InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            // Append server response in string
            sb.append(line + "\n");
        }


        text = sb.toString();
    }
    catch(Exception ex)
    {

    }
    finally
    {
        try
        {

            reader.close();
        }

        catch(Exception ex) {}
    }

}

HTTPUrlConnection Get


private void sendGet() throws Exception
 {

        String url = "http://www.google.com/search?q=androidtechi.com";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());

    }

 Below the Example exaplains ApacheHttpClient GET and POST.

 public class HttpClientExample {

    public static void main(String[] args) throws Exception {

        HttpClientExample http = new HttpClientExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();

        System.out.println("\nTesting 2 - Send Http POST request");
        http.sendPost();

    }

    // HTTP GET request
    private void sendGet() throws Exception {

        String url = "http://www.androidtechi.com/search?q=developer";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);

        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " +
                       response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                       new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());

    }

    // HTTP POST request
    private void sendPost() throws Exception {

        String url = "https://androidtechi.com/wcResults.do";

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        // add header
        post.setHeader("User-Agent", USER_AGENT);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
        urlParameters.add(new BasicNameValuePair("cn", ""));
        urlParameters.add(new BasicNameValuePair("locale", ""));
  
        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " +
                                    response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        System.out.println(result.toString());

    }

}

No comments:

Post a Comment