1
votes

I've searched here on StackOverflow and search through Google, unfortunatelly nowhere I can find an answer.

I'm trying to get the content-length of a file I'm downloading to the android app through "openConnection". File is downloading OK, but I want a progress bar which follows the progress.

In order to get that, I need to get the content-length.

The headers I have in my PHP file are:

$file_url = 'myfile.pdf';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header('Content-Length: '.filesize($file_url));
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url);

Upon a HTTP Header check online I get this:

HTTP/1.1 200 OK =>
Date => Thu, 24 Jul 2014 10:34:04 GMT
Server => Apache/2
X-Powered-By => PHP/5.3.28
Content-Transfer-Encoding => Binary
Content-disposition => attachment; filename="myile.pdf"
Content-Length => 19011079
Vary => Accept-Encoding,User-Agent
Connection => close
Content-Type => application/octet-stream

So it DOES return the content length.

During the whole process the fileSize int keeps being on -1, but the file is downloaded properly into my download directory, so that's not the problem.

Now for the strange bit, when I'm setting it directly to a JPG it DOES return the "Content-Length". Here are the headers for the JPG

HTTP/1.1 200 OK =>
Date => Thu, 24 Jul 2014 10:51:21 GMT
Server => Apache/2
Last-Modified => Thu, 24 Jul 2014 10:23:40 GMT
ETag => "506eae-10fcec-4feedd9b40300"
Accept-Ranges => bytes
Content-Length => 1113324
Connection => close
Content-Type => image/jpeg

Other things I've tried was directly linking to the PDF, which also did not return a Content-Length. I've tried uploading smaller PDF's, in the range of the JPG size also, which was unsuccessful.

1
check updated ans.. given bellow. - kamlesh

1 Answers

0
votes

I am not understanding your que..

in android you want to get content-length or in php file

if in php file then use following code

  <?php
    $url = 'http://www.google.com';

    print_r(get_headers($url));

    print_r(get_headers($url, 1));
    ?>

try following code for android java this code work perfectlly for me. make sure to use Apache HttpClient library. and you don't need to set header manually it is http's responsibility to generate header for particular request you can change header data if you want. by default it set all member field of header. this is my code

    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.mime.HttpMultipartMode;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.StringBody;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.apache.http.util.EntityUtils;

    import validationUtility.Validation;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class Login extends BaseActivity{
        private TextView tvBreadCrum;
        private static final String TAG = "Login.java";

        /**
         * content declaration
         */

        private EditText etUserName, etPaddwd;
        private TextView tvForgotPass;
        private String uname, passwd;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState,R.layout.activity_login,getApplicationContext());




            /**
             * header field initialization
             */

            tvBreadCrum = (TextView) findViewById(R.id.tv_bread_crumb);


            tvBreadCrum.setText(">> Login");


            /**
             * content initialize
             * 
             */

            etUserName = (EditText) findViewById(R.id.etUserEmail);
            etPaddwd = (EditText) findViewById(R.id.etUserPassword);
            tvForgotPass = (TextView) findViewById(R.id.tvForgotPass);
            tvForgotPass.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {


                    Intent genInquiry=new Intent(getApplicationContext(),ForgotPasswd.class);

                    startActivity(genInquiry);

                }
            });

        }


        @Override
        public void onBackPressed() {
            // TODO Auto-generated method stub
            super.onBackPressed();
            finish();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            /* Inflate the menu; this adds items to the action bar if it is present. */
            getMenuInflater().inflate(R.menu.contact_us, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.close) {
                Toast.makeText(getApplicationContext(), "Good Bye...",
                        Toast.LENGTH_LONG).show();
                finish();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        public void initVariableFields() {

            uname = etUserName.getText().toString();
            passwd = etPaddwd.getText().toString();
        }

        public boolean isValidate() {
            initVariableFields();
            boolean lbIsValid = true;
            if (!Validation.isEmailAddress(etUserName, true)) {
                return lbIsValid = false;
            } else if (!Validation.hasText(etPaddwd, "Please  your password", 5)) {

                return lbIsValid = false;
            }

            return lbIsValid;
        }

        public void reset() {

            etUserName.setText("");
            etPaddwd.setText("");
        }

        public void onSendClick(View view) {

            if (isValidate()) {
                //Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();return;

                new PostDataAsyncTask().execute();
                reset();
            }
        }

        public class PostDataAsyncTask extends AsyncTask<String, String, String> {
            private final ProgressDialog pDialog = new ProgressDialog(Login.this);

            protected void onPreExecute() {

                pDialog.setTitle("Contacting Servers");
                pDialog.setMessage("Login.......");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();

            }

            @Override
            protected void onPostExecute(final String result) {
                if (this.pDialog.isShowing()) {
                    this.pDialog.dismiss();
                }

                runOnUiThread(new Runnable() {

                    public void run() {
                        reset();
                        Toast.makeText(getApplicationContext(), result,
                                Toast.LENGTH_SHORT).show();

                    }
                });

            }

            @Override
            protected String doInBackground(String... arg0) {
                String responseStr = null;
                try {

                    Log.v(TAG, "in Back job: "
                            + "==========================Hello World");

                    String url1 = "http://lsrv.smartnet.cxm/kamleshG/Extra/postContactData/postData.php";
                    // the URL where the file will be posted
                    String postReceiverUrl = url1;

                    Log.v(TAG, "postURL: " + postReceiverUrl);
                    final HttpParams httpParams = new BasicHttpParams();
                    HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
                    // new HttpClient
                    HttpClient httpClient = new DefaultHttpClient(httpParams);

                    // post header
                    HttpPost httpPost = new HttpPost(postReceiverUrl);

                    MultipartEntity reqEntity = new MultipartEntity(
                            HttpMultipartMode.BROWSER_COMPATIBLE);

                    reqEntity.addPart("email", new StringBody(uname));
                    reqEntity.addPart("passwd", new StringBody(passwd));

                    reqEntity.addPart("submitMessage", new StringBody(
                            "AndroidSubmit"));

                    httpPost.setEntity(reqEntity);
                    /* httpPost.setEntity(new UrlEncodedFormEntity(reqEntity)); */

                    // execute HTTP post request
                    HttpResponse response = httpClient.execute(httpPost);
                    System.out.println("Printing Response Header...\n");

                    Header[] headers = response.getAllHeaders();

            //it prints whole header with content-length
                    for (Header header : headers) {
                        Log.v(TAG,"Key : " + header.getName() 
                                           + " ,Value : " + header.getValue());

                    }                   
                    System.out.println("\n Done");
                    HttpEntity resEntity = response.getEntity();

                    if (resEntity != null) {

                        responseStr = EntityUtils.toString(resEntity).trim();

                        Log.v(TAG, "Response: " + responseStr);


                    }
                } catch (Exception e) {
                    Log.e("e.getClass().getName()", "" + e.toString());
                }
                return responseStr;
            }

        }

    }  

try this link http://www.mkyong.com/java/how-to-get-http-response-header-in-java/