get HTML response Body Length - Android Network

Android examples for Network:HTTP Response

Description

get HTML response Body Length

Demo Code


//package com.java2s;

import java.net.URL;
import java.net.URLConnection;

public class Main {

    public static int getBodyLength(String url) {
        int value = -1;
        URL cURL = null;/* w w  w.j  a v  a 2 s . c  om*/
        URLConnection connection = null;
        try {
            cURL = new URL(url);
            connection = cURL.openConnection();

            connection.setDoOutput(true);
            connection.addRequestProperty("Cache-Control", "no-cache");
            connection.addRequestProperty("Connection", "keep-alive");
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.connect();

            value = connection.getContentLength();
        } catch (Exception e) {
            System.err.println("ERROR:" + e);
        }
        return value;
    }

    public static int getBodyLength(String url, String header,
            String headerValue) {
        int value = -1;
        URL cURL = null;
        URLConnection connection = null;
        try {
            cURL = new URL(url);
            connection = cURL.openConnection();

            connection.setDoOutput(true);
            connection.addRequestProperty(header, headerValue);
            connection
                    .addRequestProperty(
                            "User-Agent",
                            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
            connection.setConnectTimeout(5 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.connect();

            value = connection.getContentLength();
        } catch (Exception e) {
            System.err.println("ERROR:" + e);
        }
        return value;
    }
}

Related Tutorials