get Http Content Length - Android Network

Android examples for Network:HTTP Get

Description

get Http Content Length

Demo Code


//package com.java2s;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static String getHttpContentLength(String refence, String cookie,
            String url) {//w  ww.  j a  va2  s .c o  m
        long start = System.currentTimeMillis();
        String result = "0";
        URL urlc = null;
        HttpURLConnection conn = null;
        try {
            urlc = new URL(url);
            conn = (HttpURLConnection) urlc.openConnection();
            conn.setDoInput(true);
            if (null != refence) {
                conn.addRequestProperty("Referer", refence);
            }
            if (null != cookie) {
                conn.addRequestProperty("Cookie", cookie);
            }
            conn.addRequestProperty("Cache-Control", "no-cache");
            conn.addRequestProperty("Connection", "keep-alive");
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(10 * 1000);
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                result = String.valueOf(conn.getContentLength());
            }
        } catch (Exception e) {
            System.err.println(" > ERROR:" + e);
        } finally {
            System.out.println(" > ???????????:["
                    + (System.currentTimeMillis() - start) + "]ms");
            if (null != conn) {
                conn.disconnect();
            }
        }
        return result;
    }

    public static String getHttpContentLength(String url) {
        long start = System.currentTimeMillis();
        String result = "0";
        URL urlc = null;
        HttpURLConnection conn = null;
        try {
            urlc = new URL(url);
            conn = (HttpURLConnection) urlc.openConnection();
            conn.setDoInput(true);
            conn.addRequestProperty("Cache-Control", "no-cache");
            conn.addRequestProperty("Connection", "keep-alive");
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(10 * 1000);
            conn.connect();
            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                result = String.valueOf(conn.getContentLength());
            }
        } catch (Exception e) {
            System.err.println(" > ERROR:" + e);
        } finally {
            System.out.println(" > ???????????:["
                    + (System.currentTimeMillis() - start) + "]ms");
            if (null != conn) {
                conn.disconnect();
            }
        }
        return result;
    }
}

Related Tutorials